Another powerful feature in VBA is the ability to use project-level and application-level events to trigger the execution of some code that you have written. Project events occur when the project changes, and Application events occur when a project is created. There are fewer Project events, and they are simpler to use, so they are covered here first.
An example of a project-level event is the Project_Open event. You can write some code, and whenever that project opens, the code can automatically be executed. A typical use of the Project_Open event is to trigger setting up the environment by customizing the toolbars and menus . Another use would be to open and write to a file use log. This section uses the event to pop up a simple window.
The Project_Open event is specific to the project it exists in. You need to follow these steps to create code that will execute on the Project_Open event in your file:
Create a new project by selecting File, New.
When the file is open, go to the VBE by pressing Alt+F11.
Go to the Project Explorer. If it is not visible, you can display it by pressing Ctrl+R or selecting it from the View menu.
Navigate to the ThisProject object and double-click it. This opens a code window for the project. This code window is similar to that of the modules you created earlier. At the top of the window are two drop-down lists. On the left is the Object list. Use this list to select the Project object. This creates a shell for you, and you can write your code within this shell. Notice that the drop-down list on the right now shows Open . You can select other events from the list now.
The pj as Project part of the code specifies a Project object, just as you specified the arguments in subroutines earlier in this chapter. This gives your code an object to work with. You don't have to worry much about this because Project puts this in for you automatically.
Inside the subroutine, you want to pop up a message box indicating the project name and the last time it was saved. You do this with the following code:
MsgBox (pj.Name & vbCr & "Last Saved: " & pj.LastSaveDate)
Save the project, and the next time you open it, the code will run.
The following Project events are also available: