If a workbook contains a Visual Basic for Applications (VBA) macro that you would like to use elsewhere, you can copy the module that contains that macro to another open workbook by using the Microsoft Visual Basic Editor.
In this article
Overview of macros and VBA
If you are unfamiliar with macros and VBA in general, you may find the following information helpful.
- A macro is an action or set of actions that you can use to automate tasks.
- You can record macros by using the Record Macro command (Developer tab, Code group).
- Macros are recorded in the VBA programming language.
- You can inspect and edit your macros in the Visual Basic Editor, a window that is opened by Excel.
Macros named MakeCellGreen and SetRowHeight are in a module named Module1, which is stored in Book1.
Copying a module from one workbook to another
- If the Developer tab is not available, do the following to display it:
- Click the Microsoft Office Button , and then click Excel Options.
- In the Popular category, under Top options for working with Excel, select the Show Developer tab in the Ribbon check box, and then click OK.
- To set the security level temporarily to enable all macros, do the following:
- On the Developer tab, in the Code group, click Macro Security.
- In the Macros Settings category, under Macro Settings, click Enable all macros (not recommended, potentially dangerous code can run), and then click OK.
Important To help prevent potentially dangerous code from running, we recommend that you return to any of the settings that disable all macros after you finish working with macros.
- Open the workbook that contains the module (module: A collection of declarations, statements, and procedures stored together as one named unit. There are two types of modules: standard modules and class modules.) that you want to copy and the workbook that you want to copy the module to.
- On the Developer tab, in the Code group, click Visual Basic.
- On the View menu, click Project Explorer .
- Drag the module that you want to copy to the destination workbook in the Project Explorer (typically named VBAProject (<workbook name>).
As an example, if you copy Module1 from VBAProject (Book2.xlsm) to VBAProject (Book1.xlsm), the module will be copied as Module1 to the Modules node underneath VBAProject (Book1.xlsm).
Macro Module1 -- copied from Book2.xlsm to Book1.xlsm
Copy of macro Module1