Run Macro on A Second Workbook

crj705

New Member
Joined
Mar 16, 2022
Messages
1
Office Version
  1. 365
Platform
  1. Windows
I have FirstWB.xlsm which stores macros, and open a target workbook to run a macro stored on FirstWB.xlsm.
One thing about the macro is that, the target workbook and macro to be used are based on cell reference in L1 and L2 respectively.
The following are my codes
Sub test()

Dim SecondWB As String
Dim MacroName As String
Dim wb_macro As Workbook
Dim wb_target As Workbook

SecondWB = Range("L1").Value

Set wb_target = Workbooks.Open(SecondWB)
Set wb_macro = Workbooks.Open("PathTOFirstWB\FirstWB.xlsm")

Application.Run "'" & wb_macro.Name & "'!" & Range("L2").Value

End Sub

I am missing the code to refer macro to run on target workbook, which the code currently runs on FirstWB.xlsm where it stores macro.
Any ideas?
 

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
If you don't explicitally specify the "path", the default Workbook and Worksheet are, for a macro, the "active one".
"ThisWorkbook" always refer to the workbook that contain the macro; a "sheet codename" always refer to that worksheet.

So, in first instance the suggestion is to activate the target workbook when ready to run a macro; for example:
VBA Code:
wb_target.Activate
Application.Run "'" & wb_macro.Name & "'!" & Range("L2").Value

then check that your code always refers to the active workbook

Also be aware that Application.Run "'" & wb_macro.Name & "'!" & Range("L2").Value will get the name of the macro from the "active worksheet"; so, unless your "wb_macro" contains a single worksheet, you should better use "& Sheets("TheRightSheet").Range("L2").Value"

Bye
 
Upvote 0

Forum statistics

Threads
1,214,979
Messages
6,122,557
Members
449,088
Latest member
davidcom

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top