VBA - 从硬盘打开所有 excel 文件

VBA - open all excel files from hard drive

我看到很多代码可以打开特定文件夹中的 excel 文件。 你能帮我做一个代码来遍历我硬盘上的每个文件夹吗? 我知道这听起来很大,但是你 - 这就是我需要的..

谢谢!

添加对 Microsoft 脚本运行时 的引用(工具 -> 引用... ).然后你可以编写如下代码:

Dim fso As New FileSystemObject

Sub ParseFolder(fldr As Folder)
    Dim subfolder As Folder
    For Each subfolder in fldr.Subfolders
        ParseFolder subfolder
    Next

    Dim f As File
    For Each f In fldr.Files
        Select Case fso.GetExtensionName(file.path)
            Case "xls", "xlsb", "xlsm"
                
                ' Do something with Excel file here

        End Select
    Next
End Sub

Sub Main
    ' Run this macro to start the process running
    ParseFolder fso.GetFolder("C:\")
End Sub

根据磁盘上有多少 Excel 文件,您可能希望将代码定位到 Excel 文件的较小子集,或文件夹的较小子集;或使用 DoEvents 这样应用程序就不会冻结。


参考资料

脚本运行时