Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:est")
    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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...