用 Excel VBA 打开 .csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25163369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 08:46:45  来源:igfitidea点击:

Open .csv file with Excel VBA

excelvbaexcel-vbacsv

提问by Daniella

I'm having a problem with this piece of my code in VBA and I can't figure out why it isn't working! I've tried another code to see if it was the loop that has the issue but the issue is specifically opening the files and not iterating through them.

我在 VBA 中的这段代码有问题,我不知道为什么它不起作用!我已经尝试了另一个代码来查看是否是循环有问题,但问题是专门打开文件而不是遍历它们。

Sub fileloop(Path)
Dim strFile As String, strPath As String
Dim MyBook As Workbook

strPath = Path '& "\*.csv"
strFile = Dir(strPath & "\*.csv")

MsgBox (strFile)

While strFile <> ""

'placed another messagebox here to see if the strFile was the same inside the loop.
MsgBox (strFile)

'this line has the error.   
    Workbooks.OpenText FileName:=strFile, _
DataType:=xlDelimited, Comma:=True, Local:=True

  set MyBook = ActiveWorkbook

    Call SortColumnB(MyBook)

    strFile = Dir

 Wend

End Sub

The error message I get goes something like this:

我收到的错误消息是这样的:

'AC000W0009.csv' could not be found. Check the spelling of the file name, and verify that the file location is correct.

If you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted.

找不到“AC000W0009.csv”。检查文件名的拼写,并验证文件位置是否正确。

如果您尝试从最近使用的文件列表中打开该文件,请确保该文件未被重命名、移动或删除。

I've tried so many variations apart from the one listed above and I can't understand why VBA won't recognize that the file exists.

除了上面列出的一个之外,我已经尝试了很多变体,但我不明白为什么 VBA 无法识别该文件的存在。

EDIT

编辑

Going off of what Mike said about opening a file with the complete path the changes I made to the code to let it open .csv files:

根据迈克所说的关于打开带有完整路径的文件,我对代码所做的更改以使其打开 .csv 文件:

 strPath = Path & "\"
strFile = Dir(strPath & "*.csv")



While strFile <> ""
MsgBox (strFile)                 'added path to file name.
    Workbooks.OpenText FileName:=strPath & strFile, _
DataType:=xlDelimited, Comma:=True, Local:=True

回答by Mike

I beleve the Dir only returns only the filename.

我相信 Dir 只返回文件名。

If you want to open it, you need to add the path to the file name returned by Dir.

如果要打开,需要在Dir返回的文件名中加上路径。

There's some good examples here

有一些很好的例子在这里