简体   繁体   中英

VBA why can't I run a macro from a different document?

I have a huge macro and part of it does:

Dim wbMain As Workbook: Set wbMain = ActiveWorkbook
Dim wbData As Workbook: Set wbData = Workbooks.Open(Filename:="C:\data\MAC DOC.xlsm")
wbData.Activate
Application.Run ("'" & wbData.Name & "'!Macro_NEW")

But, on doing .Run it fails to run the macro even though whatworkbook = ActiveWorkbook.Name returns the same as wbData.Name and even trying it manually with Application.Run ("'MAC DOC.xlsm'!Macro_NEW") does the same thing.

Run-time error: 1004
Cannot run the macro: "MAC_DOC.xlsm!Macro_NEW". The macro may not be avaliable in this workbook or all macros may be disabled

Why is this coming up when the macro does exist in the MAC DOC.xlsm
Any advice welcome.

Try using the full path to name the macro, which is

WorkbookName!VBAProjectName.ModuleName.MacroName

FYI, The default project name is VBAProject and the default module name is Module1 .

(You might also consider wbData.FullName instead of wbData.Name .)

[Also, if you know that the macro is always in the active workbook I think you can leave off the prefix and just use the simple macro name -- but we don't always want to activate other workbook, so then use the full macro path name.]

Your code runs fine for me. Make sure that Macro_New is in a standard module, not a sheet or ThisWorkbook module.

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