编辑位于不同文件夹中的多个 excel 个文件全部合并在一个文件夹中

Editing multiple excel files which are in different folders all united in one folder

我在一个文件夹中有 200 个不同名称的文件夹。现在,每个具有不同名称的文件夹都有一个宏 excel 文件 (.xlsm)。我试图用一个单独的文件一次编辑所有文件。代码如下:

Sub Button1_Click()

Dim wb      As Workbook
Dim ws      As Excel.Worksheet
Dim strPath As String
Dim strFile As String

'Get the directories
strPath = "C:\Users\generaluser\Desktop\testing main folder\"
strFile = Dir(strPath)

'Loop through the dirs
Do While strFile <> ""

    'Open the workbook.
    strFileName = Dir(strPath & strFile & "*.xlsm")
    'Open the workbook.
    Set wb = Workbooks.Open(Filename:=strPath & strFile & "\" & strFileName , ReadOnly:=False)

    'Loop through the sheets.

    Set ws = Application.Worksheets(1)

    'Do whatever
    ws.Range("A1").Interior.ColorIndex = 0



    'Close the workbook
    wb.Close SaveChanges:=True

    'Move to the next dir.
    strFile = Dir
Loop

End Sub

但这行不通。我试过调整它,但无论我做什么,要么什么都不做,要么导致错误。有人可以帮我让这段代码工作吗? (另外:"testing main folder" 是我桌面上的文件夹,其中包含 200 个其他文件夹,其中包含 .xlsm 文件。)

Option Explicit 放在模块的顶部。您会遇到一些编译器错误,其中之一是 strFileName 未声明。这个 would 是一个很好的线索,可以告诉你去哪里找,因为问题是你使用的是两个变量名,当你阅读它们时,它们的含义大致相同,而且它们是混淆了。

完成变量修复后,请查看 Dir function 的文档。第二个问题是您还在循环中多次调用 Dir,这意味着您正在跳过结果。

它看起来应该更像这样:

Dim wb As Workbook
Dim ws As Excel.Worksheet
Dim file As String

'path never changes, so make it a Const
Const path = "C:\Users\generaluser\Desktop\testing main folder\"
'This returns the first result.
file = Dir$(path & "*.xlsm")

Do While file <> vbNullString
    Set wb = Workbooks.Open(Filename:=path & file, ReadOnly:=False)
    Set ws = Application.Worksheets(1)
    'Do whatever
    wb.Close SaveChanges:=True
    'This returns the next result, or vbNullString if none.
    file = Dir$
Loop