Share via


Using Events with Application and Project Objects

Project Developer Reference

You can write event procedures at the application or project level. For example, the Activate event occurs at the project level and the NewProject event occurs at the application level. The Activate event for a project occurs when the project is activated. The NewProject event occurs whenever a new project is created.

Event procedures in the Project object are available for any open project. To write event procedures for the Application object, you must create a new object using the WithEvents keyword in a class module. The following steps show how to create and test a simple application event handler.

  1. In the Visual Basic Editor, right-click VBAProject, click Insert, and then click Class Module to create a class named Class1. Rename the class module in the Properties pane, if you want. In the following examples, the class is named TestClass.

  2. Paste the following code in the TestClass module.

    
    

    Option Explicit Public WithEvents oApp As Application

    Private Sub oApp_NewProject(ByVal pj As Project) MsgBox "You created the " & pj.Name & " project." End Sub

    Private Sub Class_Initialize() ' Add class initialization statements here, if needed. End Sub

    1. Open the ThisProject module, and then paste in the following code.

      
      

      Option Explicit Private tClass As New TestClass

      Sub TestNewProjectEvent() Set tClass.oApp = Application tClass.oApp.Projects.Add Projects.Add End Sub

      1. Run the TestNewProjectEvent macro. The macro calls the Projects.Add method twice—once through the TestClass object and once directly through the Application object. When the Project application creates the first project, the result is a Microsoft Project dialog box with the message You created the Project2 project. When you click OK, Project creates the second project and shows another dialog box with the message You created the Project3 project.
      Dn690142.vs_note(en-us,office.12).gif  Note
      Event code in your project can run unexpectedly, or can be blocked, if event code exists in the global file (Global.mpt).
      • If code exists for an event in both the global and project files, only the code in the project event runs.

      • If code for an event does not exist in a project, but does in the global file, the code in the global event runs.

      • If code for one of the three events Application.ProjectBeforeClose, Application.ProjectBeforeSave, or Project.Open exists in the global file, but not in the project, it affects both the global and project files. If code exists for those events in both the global and project files, the code in the global file affects the global file, and the code in the project affects the project.