Call a macro which name is in the text of a cell

2019-09-07 06:24发布

Please your help with the following:

  1. I need to call a macro which name is variable and is in cell C5 of Sheet1 of Workbook1.
  2. I need to run that macro in another workbook, let's say Workbook2.

Code that I have (in Workbook1) so far is:

Public Sub RS()
    'Setting source worksheet and workbook where the macros are saved
    Dim ws1 As Worksheet
    Dim wb1 As Workbook
    Set wb1 = ActiveWorkbook
    Set ws1 = ActiveWorkbook.ActiveSheet

    'Defining the cell that contains the name of the chosen macro to be run
    Dim Macro1 As String
    Macro1 = Range("C5").Value

    'Selecting target workbook
    Workbooks("Workbook2").Activate
    ActiveSheet.Select
    Dim ws2 As Worksheet
    Dim wb2 As Workbook
    Set wb2 = ActiveWorkbook
    Set ws2 = ActiveWorkbook.ActiveSheet

    'Running in Workbook2, the macro selected in workbook1
    Call Macro1
End Sub

The problem is that Macro1 has not been recognized. I've been also trying with CallByName function, and Application.Run Macro1, but no luck either. Please tell me what I'm missing or what I should modify.

2条回答
欢心
2楼-- · 2019-09-07 07:19

Replace the line

    Call Macro1

with this:

    Application.Run "'" & wb2.Name & "'!VBAProject." & ws2.CodeName & "." & Macro1

Your code implies the "Macro1" is in the ws2's code module. If it is located in another module of the workbook "wb2" then replace "ws2.CodeName" above with the codename of that module.

2nd Update based on info from Flavinho.The codeline becomes this:

    'Application.Run "Workbook1.xlsm!VBAProject.Module3.ts1"
    Application.Run "Workbook1.xlsm!VBAProject.Module3." & ts1
查看更多
放荡不羁爱自由
3楼-- · 2019-09-07 07:19

To call a macro from another Workbook, you need to include the name of that workbook in Application.Run Method's first argument. Try:

Application.Run "WBNameThatContainsTheMacro.xlsm!" & Range("C5").Value

If you have multiple modules in that workbook, you can be explicit as well:

Application.Run "WBNameThatContainsTheMacro.xlsm!" & "Module1." & Range("C5").Value

Where Module1 is the name of the module. Take note of the dot that separate the module name and macro name. Is this what you're trying? HTH.

查看更多
登录 后发表回答