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

百般思念 提交于 2020-01-17 08:19:50

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/28037138/call-a-macro-which-name-is-in-the-text-of-a-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!