VBA - Do While Loop returns Dir <Invalid procedure call or argument>

喜你入骨 提交于 2019-12-18 09:44:18

问题


I am running a loop through a folder in order to get the complete filename address (folders address + file name and extension).

I am using the following, but at some point the Dir value is <Invalid procedure call or argument>

recsFolder = Functions.GetFolder("C:\")
recfile = recsFolder & "\" & Dir(recsFolder & "\*.rec*")
Do While Len(recfile) > 0
   recfile = recsFolder & "\" & Dir
Loop

The error is thrown before the loop as completed reading all the files.

EDIT: another approach and Dir is changing everytime I press F8

If Right(recsFolder, 1) <> "\" Then recsFolder = recsFolder & "\"
numFiles = 0
recfile = Dir(recsFolder)
While recfile <> ""
    numFiles = numFiles + 1
    recfile = Dir()
Wend

I am trying this latest approach and I get the same error. The problem is that when I run the code line by line (F8) I can see that the Dir value changes everytime a new line of code is run inside the While.


回答1:


Instead of DIR, how about this:

' enable Tools->References, Microsoft Scripting Runtime

Sub Test()
    Dim fso As New Scripting.FileSystemObject
    Dim fldr As Folder

    Set fldr = fso.GetFolder("C:\test")
    HandleFolder fldr
End Sub


Sub HandleFolder(fldr As Folder)
    Dim f As File
    Dim subFldr As Folder

    ' loop thru files in this folder
    For Each f In fldr.Files
        Debug.Print f.Path
    Next

    ' loop thru subfolders
    For Each subFldr In fldr.SubFolders
        HandleFolder subFldr
    Next
End Sub



回答2:


IDK it it helps but this is a pretty solid frame

 path = "yourpath" & "\"
 Filename = Dir(path & "*.fileextension")

 Do While Len(Filename) > 0
     'some code
     Filename = Dir
 Loop


来源:https://stackoverflow.com/questions/36354336/vba-do-while-loop-returns-dir-invalid-procedure-call-or-argument

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