循环以从其他工作簿运行宏

时间:2016-04-13 09:43:50

标签: excel vba excel-vba macros

我非常感谢您对我正在尝试创建的宏的帮助。

我的路径如下:K:\XXX\XXX\XXX\Module 1

Module 1是一个文件夹,其中包含一系列xlsm个以数字命名的文件(例如100.xlsm110.xlsm等等

我想创建一个循环:

  1. 运行工作簿100.xlsm;
  2. 中的宏
  3. 在宏运行完毕后保存100.xlsm(NOT"另存为")
  4. 关闭已保存的xlsm,转到下一个文件(即 110.xlsm),并重复相同的步骤。
  5. 在运行循环之前,我想创建一个存储这些xlsm文件名称的语句。

    下面的宏可能会让您了解我的目标。确实有几个错误。

    Sub update()
    
    Dim path As String path = "K:\XXX\XXX\XXX\Module 1" 
    
    Dim list() As Integer 
    List=(100, 110, 137, 140)
    
    For Each n As Integer In list   
    
      Application.Run (path & "\" &n.xslm!refresh)   
      Save WORKBOOK  
      Close WORKBOOK
    
    Next
    
    End Sub
    

1 个答案:

答案 0 :(得分:0)

我认为类似下面代码的内容将实现您想要做的事情。

请注意,代码首先打开要运行其宏的工作簿。 然后,您可以使用Application.Run()命令从原始工作簿中运行该打开的工作簿中的宏,例如,

Application.Run("book1.xlsm!mymacro"), or
result = Application.Run("book1.xlsm!mymacro", "Hello", 20)

第二个示例调用一个需要字符串参数和整数参数的宏。

下面的更全面的示例打开了一些名为100.xlsm,110.xlsm等的特定工作簿,然后在每个工作簿中运行一个名为SayHelloMessage的宏。 我希望这会有所帮助。

Sub RunMacrosInOtherWorkbooks()

   Dim wbpath As String          'path where the workbooks containing the macros you want to run are saved
   Dim wbnames() As String       'array containing names of workbooks whose macros you want to run
   Dim wbTarget As Workbook      'current workbook who macro is being run
   Dim macroname As String       'name of macro being run

   wbpath = "C:\Test"
   wbnames() = Split("100.xlsm,110.xlsm,137.xlsm,140.xlsm", ",")  'Just one way of creating the list of workbooks.
   macroname = "SayHelloMessage"

   Dim i As Integer
   Dim result As Variant
   For i = 0 To UBound(wbnames)
      Set wbTarget = Workbooks.Open(wbpath & "\" & wbnames(i))
      result = Application.Run(wbTarget.Name & "!" & macroname)
      ' result = Application.Run(wbTarget.Name & "!" & macroname, 76)  'calling a subroutine or function with an argument.  You need something to catch a return code
      wbTarget.Save
      wbTarget.Close
   Next

End Sub