如何对N个excel文件,批量执行同一个宏

要执行的宏是Macro1。
这样哪里错了?
Marco1没有定义
Sub abc()
myFile = Dir("C:\123\" & "*.xls")
Do While myFile <> ""
If myFile <> ThisWorkbook.Name Then
Workbooks.Open (myPath & myFile)
Call Marco1
Workbooks(myFile).Close
myFile = Dir
Loop
End Sub

Sub Macro1()
End Sub

首先将宏(Macro1)写入记事本,保存在特定的位置;

然后在每个工作薄中都有一个相同的宏(如“插入并运行宏”),这个宏的作用在于,临时插入(添加)宏(Macro1),宏的内容调用记事本的内容,并运行这个刚插入的这个宏(Macro1)。

------------------------------

Sub a()
    Dim myFile, myPath
    myPath = "E:\Test\"
    myFile = Dir("E:\Test\" & "*.xls")
    Do While myFile <> ""
        If myFile <> ThisWorkbook.Name Then
            Workbooks.Open (myPath & myFile)
            Set newmodule = Workbooks(myFile).VBProject.VBComponents.Add(1)
            With ActiveWorkbook.VBProject.VBComponents(newmodule.Name).CodeModule
            .InsertLines .CountOfLines + 1, _
                "Sub abc()" & Chr(13) & "MsgBox ""Hello""" & Chr(13) & "End Sub"
            End With
            Application.Run myFile & "!" & "abc"
            Workbooks(myFile).Close savechanges:=False
        End If
        myFile = Dir
    Loop
End Sub
------------------

运行的前提是

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-05-18

N个excel文件在同一路径下,可以用Dir+Do Loop遍历文件,逐个文件打开,Call Macro1即可。

下面是简要的代码,根据实际情况修改一下。

    myFile = Dir(myPath & "*.xls")
    Do While myFile <> ""
      If myFile <> ThisWorkbook.Name Then
          Workbooks.Open(myPath & myFile)
          Call Marco1
          Workbooks(myFile).Close
      myFile = Dir
    Loop

追问

我这样出错了。没有定义函数Marco1,还有目录格式对吗?
Sub abc()
myFile = Dir("C:\Users\Administrator\Desktop\123" & "*.xls")
……
End Sub

Sub Macro1()
.......
End Sub

追答

mypath后面需要有\
myFile = Dir("C:\Users\Administrator\Desktop\123\" & "*.xls")

追问

编译错误子函数(Macro1)没有定义

追答

能将Macro1的内容发上来吗?只知道错误提示无法判断具体是什么原因。

追问

你看问题补充吧,这里字数有限制

追答

Macro1里面是空的啊,所以提示Macro1没有定义,Call需要有对象。

另外需要调整Workbook.Open,没有End If

Sub abc()
    myFile = Dir("C:\123\" & "*.xls")
    Do While myFile <> ""
        If myFile <> ThisWorkbook.Name Then
            Workbooks.Open (myFile)
            Call Marco1
            Workbooks(myFile).Close
        End If
        myFile = Dir
    Loop
End Sub

Sub Macro1()
    Msgbox "Hello World"
End Sub

追问

还是有错,提示找不到文件,你自己试试

追答Sub abc()
    Dim myFile, myPath
    myPath = "E:\Test\"
    myFile = Dir("E:\Test\" & "*.xls")
    Do While myFile <> ""
        If myFile <> ThisWorkbook.Name Then
            Workbooks.Open (myPath & myFile)
            Call Macro1
            Workbooks(myFile).Close
        End If
        myFile = Dir
    Loop
End Sub
Sub Macro1()
    MsgBox "Hello World"
End Sub

文件路径变量缺少了前面的部分,现在应该可以了。

复制这次的代码测试一下。

追问

检测到无效的文件名。有些文件没执行宏,提示无效的文件名。

追答

方便把数据发给我吗?最好包含出问题的文件,我在本地测试一下。
这样不太好判断。+Q 12526174

相似回答