A reader recently asked for a discussion of automating Microsoft Project with Ruby. Let's dive right into some examples...
Create an instance of the MSProject Application class...
require 'win32ole'
app = WIN32OLE.new("MSProject.Application")
Note that Project (like Outlook and PowerPoint) is a single-instance application. This means that if an instance of Project is already running, that instance will be returned, even though you called the WIN32OLE.new method. If Project is not currently running, a new instance will be launched.
To show or hide the Application window, set the Visible property...
app.Visible = true
The application object contains a Projects collection of all open projects. To create a new project, call its Add method...
project = app.Projects.Add
Oddly, the Projects collection doesn't have an Open method. To open an existing project, call the application object's FileOpen method...
app.FileOpen('c:\temp\project1.mpp')
...then reference the active project...
project = app.ActiveProject
Use the Title method to set or get the Project's title...
project.Title = 'My Project Title'
You can iterate over the Tasks collection, and call its Add method to create a new Task...
tasks = project.Tasks
(1..100).each do |i|
task = tasks.Add
task.Type = 1
task.Name = "Task #{i.to_s}"
task.Notes = "Your comments here..."
task.Text30 = "My Specific Text"
end
A Task object has a variety of properties/methods (some shown above), and includes a Resources collection, over which you can iterate...
project.Tasks.each do |task|
puts task.Name
puts task.Resources.Count
task.Resources.each do |resource|
puts resource.Name
end
end
Save the active project by calling the Application object's FileSaveAs or FileSave methods...
app.FileSaveAs('c:\temp\project3.mpp')
app.FileSave
To exit, call the Application's Quit method...
app.Quit
As mentioned previously, there are various means for exploring the Project object model, and I encourage you to pursue these.
As always, post a comment or send me email if you have questions, comments, or a request for future topics.
Thanks for stopping by!
4 comments:
Hi!
Your explanation was simple and good!
I am working on a project which uses MS Project automation.
I am kinda new to OLE automation and I have a doubt with MSProject Automation
If I am creating a task, but if I am not setting it's type, then will it assume a default value, say 1 or 0?
Pavi:
You are correct. Microsoft Project's "Options" dialog box allows you to define the Default Task Type.
See this image:
http://www.microsoft.com/library/media/1033/technet/images/scriptcenter/office/manage/project/big/schedule.jpg
David
Very useful Information. On top of that, excellent explanation. Thanks a lot David.
Hey,
Thx for this usefull post :-)
I have a question:
When a user closes MS Project with what command in ruby do i check if it is still usable or not?
Thx!
Post a Comment