Forum Discussion
autorun macro when opening Excel
Trying to complete an open event code: to automatically run another macro when opening Excel.
Does anyone know the code for this?
- Craig HatmakerIron Contributor
So you said when Excel opens. To do that you must first learn how to run a macro when a workbook opens. So let us tackle that first
There are 3 options to 'auto run' a macro when a workbook opens:
- Auto_Open() - Create a routine named Auto_Open in a regular module. This is the most common method but the least robust (rarely doesn't run).
- Workbook_Open() - Use the Workbook Open event in ThisWorkbook. This is the second most common and a bit more robust (See below)
- Ribbon OnLoad callback- This is the hardest to implement but works every time (most robust)
For this discussion we will use the ThisWorkbook Workbook_Open event.
Under your workbook click ThisWorkbook in Project Explorer. Then select Workbook in code window then select Open in dropdown. Add code to Workbook_Open() sub which can be the code you want to run or a call to another routine to run
So now you have code that will run when this workbook opens. To make it run every time Excel opens we have 2 options:
- Save the workbook as an Add-In and make sure the add-in is loaded when we exit Excel. The next time Excel opens, the add-in loads and fires its workbook_open event.
- Save the workbook as:
C:\Users\<your user ID>\AppData\Roaming\Microsoft\Excel\XLSTART\personal.xlsm
For this discussion I recommend option 2. Here are resources to explain it in more detail:
https://analysistabs.com/excel-vba/run-macro-automatically-opening-workbook/