Automate Office PowerPoint 2007 with Visual Basic 2005
Summary: This article discusses how to automate Microsoft Office PowerPoint 2007 by using Microsoft Visual Basic 2005. We show how to use automation to start Office PowerPoint 2007, and create a presentation and slides. Also, we demonstrate how to add charts, tables, and text to the slide programmatically.
Click here to download the code sample for this article.
Creating status reports is a common requirement in many line-of-business applications that are written with Microsoft Visual Basic. However, the way in which your users end up consuming that data—probably, in a Microsoft Office application—isn't the way in which you're likely to pull it from an application. In the first two articles of this series, I showed how to use Office Word and Office Excel as a reporting tool by pulling data directly from a data source into a Microsoft Office document. By using the same concepts, you can do the exact same thing with Office PowerPoint automation, and wow your users with dynamically generated slides that are ready to insert into the status presentations that used to take hours to update.
Office PowerPoint automation is a technique for using Visual Basic 2005 to control Office PowerPoint programmatically to start, create a presentation, add content, print, save, and exit—the types of tasks that you would perform in Office PowerPoint itself. This article introduces the basics of Office PowerPoint automation: how to start and quit Office PowerPoint, as well as work with presentations. We also look at programmatically manipulating slide contents, such as text boxes, tables, and charts.
The sample application that accompanies this article illustrates each technique in this article acting as a "remote control" that automates an Office PowerPoint presentation in the background. Although we'd like to write all of your Office PowerPoint presentations for you with great content and scintillating commentary, that is unfortunately beyond the scope of this article.
This is the third article in the Visual Basic automation series and builds on concepts that were introduced in the first article, Automating the Creation of Data-Rich Business Documents with Word 2007 and Visual Basic 2005, and the second article, Automating Excel Reports: Automate Microsoft Excel 2007 with Visual Basic 2005.
Microsoft Office PowerPoint 2007 is a COM application and can be automated by using a COM object library installed with Office PowerPoint and available to Visual Basic 2005. If you have had experience writing Microsoft Office VBA macros, many of the objects that are used in automation will be familiar to you; VBA uses the same object library. Visual Basic 2005 is an unparalleled development tool for creating applications that exploit COM Interop and automation, so that the process for automating Office PowerPoint is certainly easier than ever before.
If you have had experience automating Office Excel and Office Word, you will find many of the Office PowerPoint automation concepts to be familiar. However, be aware that the automation capabilities for Office PowerPoint have some limitations. Office PowerPoint 2007 is better suited for automation than earlier versions, but it has less automation power than Office Excel and Office Word. In other words, there are things that are difficult in Office PowerPoint automation and, sometimes, impossible. Luckily, with a bit of lateral thinking, you can get around many limitations, as we will see later in this article when we cover automating charts.
Whereas Visual Basic 2005 includes F1 help for the Office Word 2007 and Office Excel 2007 automation libraries, there is no F1 help yet for the Office PowerPoint 2007 automation library. We advise looking online at the latest automation documentation, which is available in the MSDN Library here. More documentation on the Office PowerPoint 2003 object model is available in the MSDN Library here. Be aware that the documentation is light, and that there are very few reference articles available.
To automate Office PowerPoint, the basic process is to follow this set of steps:
Create an Office PowerPoint Application object.
Create a new presentation, or open an existing presentation.
Create a slide.
Add shapes to the slide.
Print or save the presentation.
The Office PowerPoint object model has about 50 objects with which you can work. In practice, however, there are only four objects with which you should really be familiar.
The Application object represents the Office PowerPoint 2007 application itself, and creating an Application object is the first step in automation. When you create an Application object, a new instance of Office PowerPoint is started, which enables you to manipulate presentations programmatically. During the process of automation, Office PowerPoint can be made visible or kept invisible. For this article, I chose to keep Office PowerPoint visible when the user clicks a button, so that they can watch the presentation building itself. Only one instance of the application object needs to be created, and you can use this single instance to manipulate multiple presentations. Be aware that closing the application object will close all instances that are running, including presentations on which the user may be working separate from automation.
After creating the Application object, the next step is to create or load a presentation. Office PowerPoint does not provide an empty presentation when it is opened via automation. The Presentation object represents a presentation in Office PowerPoint and contains many—but not all—of the properties and methods that are available through the user interface. The Presentation object is the primary object that you use to create, open, and save presentations.
Every presentation contains one or more slides. The Slide object represents a slide in a presentation, and you can add and remove slides programmatically. Like the Presentation object, the Slide object contains many—but not all—of the properties and methods that are available through the user interface.
The Shape object represents a piece of content on a slide. Slide title is a Shape; each text box is a Shape; each chart and table is a separate Shape. The Shape object offers some—but not all—of the functionality that is available through the user interface. In practice, this can make automating Office PowerPoint challenging, because navigating the properties and methods in a Shape object is a time-consuming task, and some functionality just isn't available to automation.
Let's get started by looking at the sample application that accompanies this article.
The "PowerPointAuto" sample application demonstrates how to start Office PowerPoint, create a blank presentation, add a slide and content, print, save, and exit.
First, we will need to ensure that your machine has all of the necessary prerequisites:
You will need to have Visual Studio 2005 installed, with Service Pack 1.
You will also need to install Office PowerPoint 2007 and Office Excel 2007.
After installing the prerequisites, unzip the sample files to a directory on your local hard disk. The sample consists of a solution that is named PowerPointAuto.sln and contains a single project, PowerPointAuto.vbproj, which is a Windows application with a single form that remotely controls Office PowerPoint.
Now, we're ready to walk through the sample.
Open the PowerPointAuto.sln solution.
Press F5 to compile and run the application
When the PowerPointAuto application runs, it opens a single Form that has buttons for automating Office PowerPoint.
Click the Start PowerPoint button to start Office PowerPoint via automation. Office PowerPoint will start in the background.
Now, click the Create Presentation button to create a blank presentation.
To add a slide, click the Add Slide button.
You can click this button repeatedly to add multiple slides; each new slide is added to the beginning of the presentation. To delete the first slide in the presentation, click the Delete Slide button.
The text box allows you to specify a slide title. Click the Set Slide Title button to set the title of the first slide in the presentation to the text in the text box.
Click the Add Chart button to add a chart to the first slide in the presentation.
Note that the automation code actually starts Office Excel, copies data into a sheet, and uses this data to create a chart. Why? Office PowerPoint doesn't give you full control over chart shapes. I'll discuss this in more detail later. The resulting chart is pasted into the Office PowerPoint slide.
Click the Add Table button to add a table to a slide, or click the Add Textbox button to add a text box to the slide.
Finally, click the Quit PowerPoint button to close Office PowerPoint, as well as all instances of Office PowerPoint that might be running.
The following code snippets illustrate the techniques that are used in the sample application.
You can try the following techniques in any Visual Basic 2005 client application. Before you begin, there are four things that you need to do to set up your project for Office PowerPoint automation:
Add a project reference to the "Microsoft PowerPoint 12.0 Object Library" COM object.
Add a project reference to the "Microsoft Excel 12.0 Object Library" COM object.
Import the Microsoft.Office.Interop namespace by adding the "Imports Microsoft.Office.Interop" statement to the top of any module, form, or class that contains Office PowerPoint automation code.
Import the Microsoft.Office.Core namespace by adding the "Imports Microsoft.Office.Core" statement to the top of any module, form, or class that contains Office PowerPoint automation code.
Why is Office Excel added as a reference? Office PowerPoint does not have complete automation support for working with charts, so we use Office Excel automation to create charts that are then copied into the presentation.
Starting and Quitting Office PowerPoint
To start Office PowerPoint, use the following code to create an Office PowerPoint Application object:
Dim objPPT As New PowerPoint.Application
By default, Office PowerPoint opens invisibly. We recommend making Office PowerPoint visible—so that users can see what is going on—by using the following code:
objPPT.Visible = MsoTriState.msoTrue
To quit Office PowerPoint, use the following code:
When you use the Application object, there are three important things to be aware of:
- Quitting—When you use automation to quit Office PowerPoint, every instance of Office PowerPoint that is open in Windows will also quit silently, and no prompts are given to preserve unsaved work. So, be careful.
- Speed—Office PowerPoint is a very rich application and automation adds a lot of complexity behind the scenes. Starting and quitting Office PowerPoint is not a quick operation; it may take several seconds for Office PowerPoint to start, and several seconds for Office PowerPoint to quit.
- Exception handling—When Visual Basic 2005 creates an instance of Office PowerPoint by using automation, it maintains only a loose coupling between the applications. If the Visual Basic 2005 application ends prematurely, Office PowerPoint will still remain in memory. If the user quits Office PowerPoint by using the user interface, Visual Basic 2005 will not be aware that this has happened and will generate an error when you try to use an automation object.
We recommend using structured exception handling to test the validity of each object, before you execute any block of code. The sample application shows how to do so. See How to use structured exception handling in Visual Basic .NET or in Visual Basic 2005 for an excellent explanation of how to use structured exception handling.
To create a new presentation, first start Office PowerPoint, and then create a presentation by using the Application.Documents.Add method:
Dim objPres As PowerPoint.Presentation objPPT = New PowerPoint.Application
To open a presentation, use the Application.Presentations.Open method:
Dim objPres As PowerPoint.Presentation objPres = objPPT.Presentations.Open("c:\MyPresentation.pptx")
To print a presentation, use the Presentation.PrintOut method:
To save a presentation, use the Presentation.SaveAs method:
To save the presentation in Office PowerPoint 2003 format, use the second parameter of the SaveAs method to specify the file format. The following code shows how to save a presentation in Office PowerPoint 2003 format:
objPres.SaveAs("c:\MyPresentation.ppt", _ PowerPoint.PpSaveAsFileType.ppSaveAsPresentation)
Working with Slides
A presentation contains one or more slides; these are represented as a Slides collection within each Presentation object.
Adding a slide takes a few lines of code, and you will need to work around some of the peculiarities of the Office PowerPoint automation model. To add a slide, you need to specify a custom layout. The custom layouts are stored in the presentation master and differ, depending on the presentation template. For expediency, we just choose the first custom layout in the master. After creating the slide by using the custom master, you can set the final intended layout by using the Slide.Layout method with any of the 37 slide layouts that are found in the PpSlideLayout enumeration:
Dim objSlide As PowerPoint.Slide Dim objCustomLayout As PowerPoint.CustomLayout objCustomLayout = objPres.SlideMaster.CustomLayouts.Item(1) objSlide = objPres.Slides.AddSlide(1, objCustomLayout) objSlide.Layout = PowerPoint.PpSlideLayout.ppLayoutTitleOnly
With automation, slides are added to the beginning of the presentation. You can move a slide to another position by using the Slide.MoveTo method. The following code moves the newly added slide to be the second slide in the presentation:
To delete a slide, use the Slide.Delete method:
Working with Shapes
Shapes are the most important object to understand, because a slide without shapes is empty. In an Office PowerPoint slide, every object is a shape, and the Shape object has methods and properties for every possible shape type. For example, the Shape object has a Table property that contains properties and methods for manipulating table shapes. The Table property is available on every Shape object, but it works only for Table shapes. An additional challenge is that not all of the methods and properties that you find in the Office PowerPoint user interface are exposed in the automation model. Because of these two challenges, you need to be quite aware of what type of shape you are manipulating and which properties and methods apply to it. After a little trial and error, you will be creating shapes like a professional, but use the following guide to get started.
To create a shape, use one of the Shapes.Add<Type> methods. Here is how to add a text box to a slide:
objShape = objSlide.Shapes.AddTextbox( _MsoTextOrientation.msoTextOrientationHorizontal, _ 0, 0, 400, 400)
To add a table, use the Shapes.AddTable method:
objShape = objSlide.Shapes.AddTable(3, 3)
There are 17 different Add<Type> methods—enabling you to add 17 different shape types.
To position a shape, set the Shape.Left and Shape.Top properties to position the shape on the slide, using the Twips measurement. For a standard slide, the top-left corner is (0,0) and the bottom-right corner is (720,540). You can find the width and height of a slide by using the Width and Height properties, respectively, of the slide master. For example, the following code adds a table, and then sets its size and position to occupy the entire slide:
objShape = objSlide.Shapes.AddTable(10, 10) objShape.Left = 0 objShape.Top = 0 objShape.Width = objPres.SlideMaster.Width objShape.Height = objPres.SlideMaster.Height
To delete a shape from a slide, use the Shape.Delete method:
Adding a chart to an Office PowerPoint slide poses some interesting challenges. The Office PowerPoint object model has only very limited support for adding charts. You can add a chart by using the Shapes.AddChart method:
objShape = objSlide.Shapes.AddChart(XlChartType.xl3DPie)
However, this also opens the grid for editing the chart data, not the chart itself. You cannot close the grid via automation; in fact, you cannot do anything else with the chart. You cannot change data, type, or layout. In effect, the Office PowerPoint chart automation methods are of little use.
Happily, there is a solution. Office Excel has automation support for creating charts. You can create a chart in Office Excel; set up its data, properties, and layout; and then copy it into an Office PowerPoint slide. The code to do this is straightforward, but quite lengthy. See the code in the sample to see how this is done.
There are a couple of limitations to this approach:
Both Office PowerPoint and Office Excel need to be visible during the entire process, because the process activates and selects objects in order to control the copy/paste operation.
The chart is copied as a Picture, meaning that it will break its link to the underlying data and cannot be edited after it is added to the Office PowerPoint slide.
The final effect is certainly worthwhile, because charts add a great visual element to slides.
In this article, we introduced techniques for using Visual Basic 2005 and automation to remote-control Office PowerPoint 2007. The Office PowerPoint automation model has some limitations; but utilizing Office PowerPoint automation, combined with automating other Microsoft Office applications, yields powerful and surprisingly capable results. This is the third article in the Microsoft Office automation series. Previous articles covered automating Office Word 2007 with Visual Basic 2005 and automating Office Excel 2007 with Visual Basic 2005.
Microsoft Office is an essential productivity suite for today's information workers, and Microsoft Office 2007 adds incredible power with a new focus on user-interface simplicity. With Office PowerPoint automation and Visual Basic 2005, you can automate many of the once manual tasks that information workers face, such as building data-rich slides and presentations that are composed of information that is stored in disparate systems across your organization.
About the author
Ed Robinson is the coauthor of Upgrading Microsoft Visual Basic 6.0 to Microsoft Visual Basic .NET and Security for Microsoft Visual Basic .NET, as well as numerous technology articles. Ed is the CIO for Intergen Ltd, one of New Zealand's most prominent Microsoft Gold Certified Partners.