简体   繁体   English

使用Excel VBA打开.csv文件

[英]Open .csv file with Excel VBA

I'm having a problem with this piece of my code in VBA and I can't figure out why it isn't working! 我在VBA中的这段代码有问题,我不知道为什么它不起作用! 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. 我尝试了另一个代码,看是否是有问题的循环,但问题是专门打开文件而不是遍历文件。

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. 找不到“ AC000W0009.csv”。 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. 如果尝试从最近使用过的文件列表中打开文件,请确保未重命名,移动或删除该文件。

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: 迈克(Mike)关于用完整路径打开文件的说法与我对代码的更改有关,以使它可以打开.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

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 有一些很好的例子在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM