Open .csv file with Excel VBA

蹲街弑〆低调 提交于 2020-01-07 05:01:08

问题


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.

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.

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.

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:

 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

回答1:


I beleve the Dir only returns only the filename.

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

There's some good examples here



来源:https://stackoverflow.com/questions/25163369/open-csv-file-with-excel-vba

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