2016-07-18 47 views
0

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

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文件。)

+0

[这个答案](http://stackoverflow.com/questions/22645347/loop-through-all-subfolders-using-vba)将帮助你了解如何遍历子文件夹。 –

+1

[循环通过用户指定的根目录中的子文件夹和文件]可能的重复(http://stackoverflow.com/questions/14245712/cycle-through-sub-folders-and-files-in-a-user -specified-root-directory) – Comintern

回答

0

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 
+0

这仍然不能打开**子文件夹中的'.xlsm'文件** –

+0

@ScottHoltzman - 我没有看到关于子文件夹的任何问题,但了解如何迭代一个目录是无疑是迈向正确方向的一步。 – Comintern

+0

重读前两句话的问题 –

相关问题