9.22.2008

Working with the Project Object

The Second in a Series of Short Notes About Using Project VBA

Using a Project object of some kind is essential to programming Project. Like the Task object, it is also a member of a collection, in this case it is part of the Projects collection. Although the Projects collection is under the Application it is what Microsoft calls a "top-level object" meaning that you can use it without needing to specify the Application. This means both of the following are equivalent within Project (though if you are controlling project from another application you will want to specify the application just to be clear):

Application.Projects
is the same as:
Projects

The Project object I use most often is the ActiveProject. ActiveProject is simply the project you are currently working on in project. If you have multiple projects open then it is the one which is in front and which has the cursor active in it. Most of the time you want your code to operate on the ActiveProject and not some other project so code typically looks like this:

Set ts as ActiveProject.Tasks

There are cases where you DO want to work on all the projects that are open. In this case you would forgo using ActiveProject and refer to them individually. You can use For..Next to go through all of the open projects:

For Each Project In Application.Projects
'run subprocedure
Next Project

The Project object can refer to any project and you can define as many as you like. This can be useful when you want to compare a project which is open with another.

Dim proj1 as Project
Dim proj2 As Project
Set proj1 = ActiveProject
Set proj2 = FileOpen("c:\myfilename.mpp")
If proj2.Tasks(5).Finish = proj1.Tasks(5).Finish Then
msgbox "Task 5 is unchanged."
End if
End Sub

You can use an index to refer to a specific project, though the index of the project is dependent on the order in which the files were opened, so there is room for some surprises here:

Set proj1 = Application.Projects(1)
Set proj2 = Application.Projects(2)

There is another interesting type of Project and that is the SubProject. Subprojects are any projects inserted in a "Master" project. Sometimes it is necessary to go through them as well. An example is setting a particular view or modifying some information which can not be done in the "Master" view.

Dim subproj As Subproject
Dim myproj As Project
'go through all the subprojects in the file
For Each subproj In ActiveProject.Subprojects
'open them all in turn
FileOpen (subproj.Path)
Set myproj = ActiveProject
'when open do something to the file
FileClose
Next subproj

The Projects collection has a small number of properties including count, parent and item. It also has a method to add a project. Project and SubProject have too many properties to describe here, but eventually I'll get around to covering some of the more interesting ones.

last-Samu1241's Blog © 2008. Template by Dicas Blogger.

TOPO