简体   繁体   中英

Run an identical macro from another workbook

First let me explain why I am asking this question so its clear that I need more than the Application.run command. If someone has a way solving the problem by other means it would also be good.

I created a program that will make a new excel file with macro's and codes that is a new program on it's own. I did this because I don't want the original file to change. The original file is the template for all new created files.

But when I run my code I get a lot of errors with sheet names that are not in the original file but that are in the new file. So, in some way the Activeworkbook changes and I don't know why. When I run the code I changed the Activeworkbook to the new file.

I was hoping to solve this by running the macro's from the newly file and making sure these macro's will only work with the newly created workbook and not with the original ones. The problem is that the macro's in the original workbook and new workbook are identical, I copied the modules.

So my question : Is there a way that I run a macro with an identical name from another workbook in VBA-Excel. It is important that this macro will only access macro's from it's own workbook!

Thanks in advance

I believe the following demonstrates what you need to do.

I have created two workbooks: "TryDup1.xls" and "TryDup2.xls".

"TryDup1.xls" contains the following code in a module:

Option Explicit
  Sub CtrlDup()

    Dim PathCrnt As String
    Dim WBookOrig As Workbook
    Dim WBookOther As Workbook

    Call DupMac(1)

    Set WBookOrig = ActiveWorkbook
    PathCrnt = ActiveWorkbook.Path & "\"

    Set WBookOther = Workbooks.Open(PathCrnt & "TryDup2.xls")

    Call Application.Run("TryDup1.xls!DupMac", 2)

    Call Application.Run("TryDup2.xls!DupMac", 3)

    WBookOther.Close SaveChanges:=False

    Call DupMac(4)

End Sub
Sub DupMac(Param As Long)

  Debug.Print "TryDup1's DupMac: Param=" & Param

End Sub

"TryDup2.xls" contains the following code in a module:

Option Explicit
Sub DupMac(Param As Long)

  Debug.Print "TryDup2's DupMac: Param=" & Param

End Sub

Opening "TryDup1.xls" and executing CtrlDup() causes the following to be output to the Immediate window:

TryDup1's DupMac: Param=1
TryDup1's DupMac: Param=2
TryDup2's DupMac: Param=3
TryDup1's DupMac: Param=4

So macro CtrlDup() can run either version of macro DupMac().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM