The following VBA procedure is designed to automatically execute when a specific workbook is opened. In this example, it shows a message with the name of the current workbook and opens another workbook from a specified location.
Example Code: Workbook_Open Event
Private Sub Workbook_Open() MsgBox ActiveWorkbook.Name Workbooks.Open "C:\Users\POPOLY\document_name.xlsm" End Sub
Explanation:
What is Workbook_Open()?
- Workbook_Open() is a workbook-level event that runs automatically when the workbook is opened.
- It must be placed inside the ThisWorkbook module, not in a regular module or sheet module.
- This makes it useful for initializing settings, showing messages, loading data, or opening other workbooks.
What this Procedure Does:
Displays a message box showing the name of the workbook that was just opened:
MsgBox ActiveWorkbook.Name
Opens another workbook located at:
Open « C:\Temp\Mappe1.xlsm »
This assumes that the file exists at the given path.
How to Test It:
To see this code in action:
- Close all Excel instances completely.
- Open the file Mappe2.xlsm (which contains this macro in ThisWorkbook).
- When the file opens:
- A message box will show the workbook name (Mappe2.xlsm).
- Then, Mappe1.xlsm will open automatically from C:\Temp.
✅ Important:
- Ensure macros are enabled when you open xlsm.
- The path C:\Temp\Mappe1.xlsm must be correct and accessible.
- You may need to adjust the file path depending on your environment.
Summary
- Use Workbook_Open() in ThisWorkbook to trigger actions when a workbook opens.
- Ideal for loading additional workbooks, initializing settings, or preparing the interface.
- Combine it with error handling (e.g., On Error Resume Next) for robustness if the file doesn’t exist.