Creating Macros


Chapter 27 describes how to create a macro by recording the steps that make up a task. Although creating macros this way is easy enough and does work, it's not the most effective way to write Visual Basic, especially as your development skills grow. Creating macros in the Visual Basic Editor also enables you to use many more tools to develop Visual Basic solutions than are provided by recording actions in the Microsoft Project interface.

Writing a Macro in the Editor

Writing macros directly in the editor can seem a little daunting if you don't have much experience with programming or if you aren't comfortable with the object model. There are few tools to help you start (other than the Add Procedure window, which you can find by clicking Insert, Procedure), so one way to begin is to simply record a macro and then edit it in the Visual Basic Editor.

For the purposes of this discussion, though, you can simply follow these steps to create a macro in the editor directly:

  1. Create a new project and then open the Visual Basic Editor by pressing
    Alt+F11.

  2. Double-click the ThisProject object in the Project Explorer.

    The Code window opens with the cursor in the upper-left corner.

  3. Type the following code in the Code window:

     Function strNewTask(strName As String, intBefore As Integer) As String     ActiveProject.Tasks.Add strName, intBefore         If ActiveProject.Tasks(intBefore).Name = strName Then         strNewTask = "Success!"     Else         strNewTask = "Failed to create task!"     End If End Function 
    Note  

    Be sure to capitalize variable names exactly as they are shown here.

    • As you enter the code, you will notice some things that the editor does:

    • As you type strName As in the function definition, a list displays classes and data types. As you start typing String , the list scrolls until String is selected (see Figure 31-12). You can continue typing the word, select String from the list, or press Ctrl+Space to complete the word.

      click to expand
      Figure 31-12: The Auto List Members feature scrolls through an alphabetical list of possible matches for data types and constants as you type.

    • When you press Enter at the end of the line containing the function definition, several things happen at once: As the word "function" is capitalized, a blank line and End Function are inserted, and Visual Basic keywords (Function, String, Integer, and so on) are colored blue.

    • When you press Enter at the end of a line containing an equals sign (=), the editor puts spaces around the equals sign.

  4. Type the following code in the Code window:

     Sub AddTask()     Dim strTaskName As String     Dim intTaskNum As Integer          strTaskName = InputBox$("Type a name for the new task:")     intTaskNum = CInt(InputBox$("Type the position for the new " & _       "task in the task list:"))         MsgBox strNewTask(strTaskName, intTaskNum) End Sub 

    As you enter this code, the same actions occur as when you entered code for the function, but something really interesting also happens: Typing strnewtask ( causes the Quick Info feature to list information about the arguments and return value for strNewTask (see Figure 31-13).

    click to expand
    Figure 31-13: The Quick Info feature lists details about procedures you create and about items in the object model.

Returning to the Microsoft Project interface and opening the Macros dialog box (click Tools, Macro, Macros) shows the AddTask procedure as a new macro.

Tip  

Switch between Microsoft Project and the Visual Basic Editor       After the Visual Basic Editor has been opened, Alt+F11 toggles between Microsoft Project and the editor.

Deciding Where to Create and Store Procedures

The discussion so far has been about creating procedures in the ThisProject object for the VBAProject project, but that might not always be the best place to create procedures. In deciding where to create procedures, you should think about what the code is meant to do and whether you want to distribute your code to other people.

Depending upon your needs and the type of code you're writing, you should create procedures in the following areas:

  • The ProjectGlobal project, if you want your procedures available for every plan you work with. Procedures in the ProjectGlobal project are associated with the Global file, which is opened every time you start Microsoft Project.

  • The VBAProject project, if the procedures are used only for that particular plan. Procedures in the VBAProject project are associated with that particular plan and are available to anyone who opens the plan.

  • A code module, if you want to be able to easily distribute the code to other people. Modules can be easily distributed because they are not associated with any particular plan and can be imported into a project as needed. Also, because they are not associated with any plan, modules are a good place to store general "utility" code.

    Note  

    To add an existing module to a project, right-click the project in the Project Explorer, click Import File, and then browse to the file that you want to insert.

Working with Events

Macros require user action to start, but you might occasionally need code to start automatically. For example, every time a shared plan is saved, you might want to store information about the person who saved it. In a situation like that, you need code that is run from an event procedure .

An event procedure is any code that is tied to an event, such as when a plan is saved or a task is deleted. When the event fires , the code is activated. Anything you can do in a "regular" procedure you can also do in an event procedure, including calling other procedures and making references to other object models.

Cross-References  

For more information about events in UserForms, such as Click events for buttons , see "Creating UserForms" later in this chapter.

In Microsoft Project, there are events attached to the Application and Project (representing an open plan) objects (see Figure 31-14). You can find the events by looking for the event icon in the object browser or by expanding the Events item in the Contents tab of the Microsoft Visual Basic Reference.

click to expand
Figure 31-14: The ApplicationBeforeClose event is a member of the Application object.
Note  

Sort items by type       To sort items in the object browser by type instead of simply alphabetically , right-click anywhere in the object browser and then click Group Members.

Creating Application Event Procedures

Creating Application event procedures is a three-step process. The first step is to create a class module that contains an Application object variable declared with events. WithEvents is a Visual Basic keyword that means the variable should respond to events. You can only use WithEvents in class modules.

The second step is to bind the class containing your event procedure to the Application object. You do this by first declaring a variable that represents the class module and then writing a procedure that assigns the variable to the Application object.

For the last step, you need to decide how to run the code that binds the class to the Application object. You can either write the binding code directly in a project-level event procedure or if you want to keep your code more modular, you can write it anywhere you like and then simply call it from a project-level event.

Follow these steps to create an event procedure for the Application object:

  1. Right-click anywhere in the Project Explorer and then click Insert, Class Module.

  2. In the Code window for the new class, enter the following code:

     Public WithEvents objMSProjectApp As Application 
    Note  

    The variable represented here by objMSProjectApp can be named anything you like.

  3. In the Objects box, select objMSProjectApp.

    The editor creates a blank procedure for the NewProject event. If you want to write a procedure for a different event, click it in the Procedures/Events box.

  4. Write your event code as you would for any other procedure.

    For example, the following code prevents a particular resource from being assigned to tasks. (Note that the procedure declaration must be entered on one line in the Visual Basic Editor, not on three as shown here.)

     Private Sub objMSProjectApp_ProjectBeforeAssignmentChange(ByVal asg As  Assignment, _   ByVal Field As PjAssignmentField, ByVal NewVal As Variant, _     Cancel As Boolean)          If Field = pjAssignmentResourceName And _       NewVal = "Patricia Doyle" Then         MsgBox "Patricia is no longer available for assignment!"         Cancel = True     End If End Sub 
  5. Change the Name field in the Properties window for the class from Class1 to clsAppEventProcedures.

  6. In any module except the class module in which you wrote the event procedure, enter the following code in the Code window:

     Dim clsAppEvents As New clsAppEventProcedures     Sub BindEventToApplication()     Set clsAppEvents.objMSProjectApp = Application End Sub 
  7. Double-click ThisProject in the Project Explorer to open the Code window, click Project in the Objects box, and then type the following code in the Project object's Open event:

     BindEventToApplication 

Creating Project Event Procedures

To create an event procedure for the Project object, the code must be written in the ThisProject object, rather than in a code module. Events for the Project object are attached to the plan, which ThisProject represents.

Follow these steps to create an event procedure for the Project object:

  1. Double-click ThisProject in the Project Explorer to open the Code window.

  2. In the Objects box, click Project.

    The editor creates a blank procedure for the Open event. If you want to write a procedure for a different event, click it in the Procedures/Events box.

  3. Write your event code as you would for any other procedure.

    For example, the following code adds information to the plan's summary task about who saved the plan, and when, each time it is saved:

     Private Sub Project_BeforeSave(ByVal pj As Project)     Dim strName As String         strAlias = InputBox("Please enter your name: ")     pj.ProjectSummaryTask.AppendNotes vbCrLf & "Saved by " & _       strName & " on " & Date$ & " at " & Time$ & "." End Sub 



Microsoft Office Project 2003 Inside Out
Microsoft Office Project 2003 Inside Out
ISBN: 0735619581
EAN: 2147483647
Year: 2003
Pages: 268

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net