I need to import a csv file, but VBA/Excel is very bad at formating it. The only way I found is to first copy the file as .txt then import it with Workbooks.OpenText
.
Here is the code (functionnal and good)
Sub CopierDonneesDepuisCSV()
' Convert .csv into a .txt, import .txt then delete it
' Usefull when Excel doesn't know how to parse csv...
Dim Newsheet As String
Newsheet = ThisWorkbook.Sheets(importSheet).Range("fileDate").Value 'path file
Dim ws As Worksheet
Set ws = Sheets(templateSheet)
ws.Copy After:=ws
ActiveSheet.Name = Newsheet
With Worksheets(Newsheet)
.Range("B4").Value = ThisWorkbook.Sheets(importSheet).Range("filePath").Value
.Range("B5").Value = ThisWorkbook.Sheets(importSheet).Range("fileDate").Value
.Range("B6").Value = ThisWorkbook.Sheets(importSheet).Range("commentaire").Value
.Range("B7").Value = ThisWorkbook.Sheets(importSheet).Range("auteur").Value
.Range("B8").Value = ThisWorkbook.Sheets(importSheet).Range("hash").Value
.Range("B11").Value = ThisWorkbook.Sheets(importSheet).Range("nbGen").Value
.Range("B12").Value = ThisWorkbook.Sheets(importSheet).Range("timeout").Value
.Range("B13").Value = ThisWorkbook.Sheets(importSheet).Range("efficiency").Value
' Creating the .txt file
Dim data_csv As Workbook
pathTxt = ThisWorkbook.Sheets(importSheet).Range("filePath").Value & ".txt"
FileCopy ThisWorkbook.Sheets(importSheet).Range("filePath").Value, pathTxt
Workbooks.OpenText Filename:=pathTxt, Comma:=True, DataType:=1, TrailingMinusNumbers:=False
Set data_csv = ActiveWorkbook
data_csv.Sheets(1).Range("A2:K60").Copy
.Range("E16:O100").PasteSpecial Paste:=xlPasteValues
data_csv.Sheets(1).Range("A2:A60").Copy
.Range("A17:A100").PasteSpecial Paste:=xlPasteValues
data_csv.Close False
' Deleting the .txt file
Kill ThisWorkbook.Sheets(importSheet).Range("filePath").Value & ".txt"
End With
Call ImportTextFile
End Sub
The problem, is that this code creates an empty VBAproject everytime I run the macro, named after the .txt file.
- Why is it creating a project ?
- I tried to delete “VBAProject”, “Microsoft Exel Objets” and “Feuill1” with mouse right-click, but I cannot. How do I delete them ?
Thank you