【问题标题】:Editing multiple excel files which are in different folders all united in one folder编辑位于不同文件夹中的多个excel文件都合并在一个文件夹中
【发布时间】:2016-07-18 21:26:11
【问题描述】:

我在一个文件夹中有 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

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

【问题讨论】:

标签: vba excel subdirectory


【解决方案1】:

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

完成变量修复后,请查看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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-25
相关资源
最近更新 更多