I developed a macro in a specific worksheet (for example: worksheet 1), but I want to run this macro in another worksheet (worksheet 2) without having to open the source code (worksheet 1).
Is there any way to call it?
Regards,
You cannot run VBA code located in a Closed workbook. However, you can still run code from another workbook that is currently open. You can use VBA code in your current workbook that can automatically open the other workbook, run the code, then close the workbook.
So to open a workbook, Workbooks.Open
. To run the macro in that workbook, you will need to use Application.Run "FileName.xlsm!YourMacroNameHere"
.
There is one thing you will need to be aware of when running code from another workbook. If the code makes references to that workbook only, then your code will not make changes in the new workbook.
Example:
If the code you are using says things such as Set Ws = ThisWorkbook.Worksheets()
, then anything that references Ws
will not update the book that called it (hence, it will not reference the book with the code Application.Run
)
Although the approved answer is correct, there is also such a thing as the "Personal Macro Workbook". You can find this workbook when trying to record a new macro, in the "store macro in" dialog. This workbook is available across all your workbooks and does not need to be opened for your macros to run.
Sub Test
, in sheet 2's code, typeTest
orCall Test(Variables)
. If it's aPrivate Sub
, you can typeCall Sheet.Test
Alt+F8
? If that is what you are talking about, go to your modules and make sure they are not showingPrivate Sub
, you can change toPublic Sub
or justSub
.