首页 > 解决方案 > 第一次迭代后循环文件夹中的所有文件失败

问题描述

我正在尝试通过一个文件夹中的所有文件循环一个宏。第一次迭代后,我收到错误“无效的过程调用或参数”。这可能是什么原因造成的?该文件夹包含许多 xlsx 和 csv 文件。宏设置为仅在 xlsx 文件上运行。

Sub Step18LoopAllFilesInAFolder()

    folderName = "D:\Users\Desktop\Macro Data\Test"
    If Right(folderName, 1) <> Application.PathSeparator Then folderName = folderName & Application.PathSeparator
    Fname = Dir(folderName & "*.xlsx")

    'loop through the files
    Do While Len(Fname)

        With Workbooks.Open(folderName & Fname)

           Call Step17MasterMacro


        End With

        ' go to the next file in the folder
        Fname = Dir

    Loop

End Sub

标签: excelvba

解决方案


根据@braX 的建议,我更改为以下内容。奇迹般有效!

Sub Step18LoopAllFilesInAFolder()
    Dim FSO As Object
    Dim folder As Object
    Dim wb As Object

    Set FSO = CreateObject("Scripting.FileSystemObject")
    folderPath = "D:\Users\Desktop\Macro Data\Test"
    Set folder = FSO.GetFolder(folderPath)


    For Each wb In folder.Files
        If Right(wb.Name, 4) = "xlsx" Then
            Set masterWB = Workbooks.Open(wb)
            Call Step17MasterMacro
        End If
    Next
End Sub

推荐阅读