Import semicolon separated CSV file using VBA

徘徊边缘 提交于 2019-12-31 01:07:26

问题


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:

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:

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?


回答1:


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:=FileName:=strPath & "thisFile.txt", DataType:=xlDelimited, Semicolon:=True, DecimalSeparator:=",", ThousandsSeparator:="."


来源:https://stackoverflow.com/questions/39890471/import-semicolon-separated-csv-file-using-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!