Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

excel - Import semicolon separated CSV file using 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:="."

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...