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!