Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import semicolon separated CSV file using VBA

Tags:

csv

excel

vba

I have a problem with opening .csv files with Excel by VBA code. I have data organised like:

Number;Name;Price1;Price2;City 
1234;"John Smith";"1,75 EUR";"2,15 EUR";"New Mexico" 
3456;"Andy Jahnson";"12,45 EUR";"15,20 EUR";London 
3456;"James Bond";"42,34 EUR";"9,20 EUR";Berlin

When I open this file manually by Excel from Windows Explorator, everything looks fine, all values are separated correctly. It looks like that:

Example1

When I try to open this by VBA, using

Workbooks.Open fileName:=strPath & "thisFile.csv"

data is separated by commas, so it looks like that:

Example2

The same wrong result pops out when I am using OpenText function

Workbooks.OpenText filename:=strPath & "thisFile.csv", DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=True, Comma:=False, Space:=False, Other:=False

and when I try use solution from this thread. Any ideas?

like image 690
Limak Avatar asked Oct 06 '16 07:10

Limak


1 Answers

I hope you are using something newer than Excel 2000. This is what I experience with Excel 2016 on a machine with German format settings: Apparently the Workbooks.Open options for delimiters (Format and Delimiter) are only applied when you open a .txt file. If Local is set to False (the default value), the file will be opened with the VBA language settings, using a comma as delimiter. Setting Local:=True will prevent this so

Workbooks.Open FileName:=strPath & "thisFile.csv", Local:=True

should work for you. If you rename your file to .txt, you can use the Format and Delimiter options:

Workbooks.Open FileName:=strPath & "thisFile.txt", Format:=4 'Format = 4 is semicolon delimited
Workbooks.Open FileName:=strPath & "thisFile.txt", Format:=6, Delimiter:=";" 'Format = 6 is custom delimited

See MSDN for more details
However this will mess up your decimal numbers, see my edit.


Edit: I misread the documentation. The Format and Delimiter options are actually only applied when using a .txt file and not .csv (even the .OpenText method behaves that way).

If you want to make sure it opens on a machine with different format settings the only solution I have right now is to rename it to .txt and use

Workbooks.OpenText FileName:=strPath & "thisFile.txt", DataType:=xlDelimited, Semicolon:=True, DecimalSeparator:=",", ThousandsSeparator:="."
like image 111
arcadeprecinct Avatar answered Nov 07 '22 09:11

arcadeprecinct