使用Excel VBA打开.csv文件

我在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 

我得到的错误信息是这样的:

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

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

我已经尝试了很多变化,除了上面列出的,我不明白为什么VBA不会识别该文件存在。

编辑

迈克说,关于打开一个完整的path的文件,我对代码打开.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 

我只是说Dir只返回文件名。

如果要打开它,则需要将path添加到由Dir返回的文件名。

这里有一些很好的例子