I am trying to open all csv (separator is semicolon) files in a directory and this is the code that I think should work:
Sub test()
Dim MyFile As String
Dim MyDir As String
MyDir = Application.ActiveWorkbook.Path
MyFile = Dir(MyDir & "\" & "*.csv")
'set current directoy
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While MyFile <> ""
Workbooks.Open (MyFile)
'Parse it using semicolon as delimiters
Range(Range("A1"), Range("A1").End(xlDown)).TextToColumns _
DataType:=xlDelimited, _
ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=True, Comma:=False, Space:=False, Other:=False '
'next file in directory
MyFile = Dir()
Loop
End Sub
But strangely, it also uses comma as a separator as well. I can see that if I debug the TextToColumns
line.
So for a csv file like
test;test,test
I would expect an output of
test test,test
But I actually get
test test
Why? Is there something wrong with my Excel settings?
Thanks!
The problem is with this line
The moment you open the file in Excel, it is opened in this format as it is a Comma Delimited File
And then when the
.TextToColumns
code runs it replaces ColumnB
data with the "test" which is after;
in ColumnA
.Try this
Let's say your csv file looks like this
Now try this code. Once you understand how it works, simply adapt this in your code. I have commented the code so that you will not have a problem understanding it.
And this is what you get
EDIT: The other option that you have is to rename the csv file and then open it as suggested in Open csv file delimited by pipe character “|” or not common delimiter