Skip to main content
Create an Application-Level Add-In to Automate Common Office Tasks

Robert Green

MCW Technologies,LLC

Sinceits inception, Visual Studio Tools for Office has provided developers with apowerful set of tools for building solutions for the Microsoft Office System.There has never been a better time to build solutions that combine familiar.NET coding techniques with the most familiar user interface around.

Youcan also use VSTO to build application-level add-ins that automate commontasks. This has traditionally been one of the strengths of Visual Basic forApplications (VBA). VSTO provides a more secure and powerful model forautomating Office applications using either Visual Basic or C#.

Forexample, suppose you want to print a PowerPoint presentation. You want to printblack and white handouts with three slides per page. To do this, you need totake the following steps:

  • Click the Office Button.
  • Click Printto display the Print dialog box.
  • Select Handoutsin the Print what drop-down list.
  • Select PureBlack and White in the Color/grayscale drop-down list.
  • Select 6in the Slides per page drop-down list.
  • Check Frameslides.
  • Click OK.

Asan alternative, you can create a PowerPoint add-in that adds buttons to theRibbon to programmatically accomplish tasks like this. In this tutorial, youwill create the customization shown in Figure 1.You will add a group to the Ribbon that contains four buttons. The first twobuttons print the current presentation as black and white handouts with threeor 6 framed slides per page. The last two buttons save the presentation as aPPT file using the PowerPoint 97 – 2003 format or as a PPTX file using thePowerPoint 2007 format.

Figure1.jpg

Figure1. These Ribbon buttons perform commontasks in PowerPoint.

Usingthese buttons, each of these tasks can now be perfomed with no more than twomouse clicks, one to bring forward the Ribbon tab and one to select theappropriate button.

Create a PowerPoint Add-in

Toget started, in Visual Studio 2008 select File| New | Project to display the New Project dialog box. In the list ofproject types, expand the Office node. Select Version2007, displaying the list of templates shown in Figure 2.

2. Visual Studio 2008 provides these Office2007 templates.

Ifyou want to write code that is available when a particular document is open,you can select the Excel Workbook or Template or Word Document or Templateproject templates. If you want to create a customization that is alwaysavailable, you can select the Excel, InfoPath, Outlook, PowerPoint, Project,Visual or Word Add-in project templates. For this tutorial, select the PowerPoint 2007 Add-in template. Nameyour project PowerPointCommonTasksAddIn.Click OK to create the project.

Youhave two options for customizing the Ribbon in Office applications. You canwrite Ribbon XML or you can use the Ribbon Designer. You’ll take the secondapproach here. Select Project | Add New Item. In the Add New Itemdialog box, select the Ribbon (VisualDesigner) item template and click Add.Visual Studio opens the Ribbon Designer (see Figure 3).

Figure 3. Use the Ribbon Designer to customize theRibbon.

SelectGroup1 and change the Label property to CommonTasks. From the Toolbox, drag four Button controls into the Common Tasksgroup. Name the first button print3Button.Set the Label property to Print 3and the SuperTip property to Print handoutswith 3 slides per page.

Youhave two choices for button size: regular or large. You will use large buttonshere, so set the ControlSize property to RibbonControlSizeLarge.You also have the option of including an image with your button in addition tothe label. In general, Ribbon buttons have an image, so you will typicallyspecify one. To use a custom image, click the ellipsis associated with theImage property. This displays the Select Resource dialog box. You can thenselect a local or a project image resource. This is the same technique youwould use to add an image to the button on a Windows Form.

Youcan also use a built-in Office images. To do that, set the OfficeImageIdproperty to the id of the image you want. Here, set the property for the buttonto FilePrintQuick.

Howdo you know what id to use? One easy way to find the id is to right-click onthe Ribbon or the Quick Access Toolbar and select Customize Quick Access Toolbar. This displays the PowerPointOptions dialog box. Find the command that includes the icon you want anddisplay the command’s tooltip. You will find the id in parentheses (see Figure 4).

Figure 4. You can use the Options dialog to findthe ids for built-in Office images.

Anothereasy way is to use the VSTO Ribbon IDs Power Tool. You can download and installthis from http://www.microsoft.com/downloads/details.aspx?FamilyId=46B6BF86-E35D-4870-B214-4D7B72B02BF9&displaylang=en. This tool adds anImageMso Window item to the Tools menu in Visual Studio. Select that menu itemto display the ImageMso Values dialog box. Type print in the search box and click the magnifying glass. The buttonswith print in the id name appear (see Figure 5).When you click the image you want, the tool copies the id to the clipboard.

Figure 5. You can use the VSTO Ribbon IDs PowerTool to find the ids for built-in Office images.

Returnto the Ribbon Designer. Name the second button print6Button. Set the ControlSize property to RibbonControlSizeLarge, the Label property to Print 6, the SuperTip property to Print handouts with 6 slides per page and the OfficeImageIdproperty to FilePrintQuick.

Namethe third button saveAsPPTButton.Set the ControlSize property to RibbonControlSizeLarge,the Label property to Save As PPT,the SuperTip property to Save thispresentation as a PPT and the OfficeImageId property to FileSaveAsOtherFormats.

Namethe fourth button saveAsPPTXButton.Set the ControlSize property to RibbonControlSizeLarge,the Label property to Save As PPTX,the SuperTip property to Save thispresentation as a PPTX and the OfficeImageId property to FileSaveAsOtherFormats. The RibbonDesigner should look like Figure 6.

Figure 6. The Ribbon Designer should look likethis.

Saveyour changes and build the solution. To see what this looks like in PowerPoint,press F5. The Common Tasks group isadded to the Add-Ins tab on the Ribbon and the four buttons appear with thedesired images (see Figure 7).

Figure 7. The Common Tasks group is added to theAdd-Ins tab of the Ribbon.

Write Code That Runs When You Click a Button

Yournext step is to write the code that will perform a task when you click each ofthese buttons. Quit PowerPoint and return to Visual Studio.

Inthe Ribbon Designer, double-click the Print 3 button. Add the following code tothe print3Button_Click event handler:

With Globals.ThisAddIn.Application.ActivePresentation
  .PrintOptions.OutputType = _
    PowerPoint.PpPrintOutputType.ppPrintOutputThreeSlideHandouts
  .PrintOptions.PrintColorType = _
    PowerPoint.PpPrintColorType.ppPrintPureBlackAndWhite
  .PrintOptions.FrameSlides = Office.MsoTriState.msoTrue
  .PrintOut()
End With

This AddIn represents the add-in itself.This AddIn Application represents the application in which the add-in runs, inthis case PowerPoint. ActivePresentation represents the presentation that iscurrently open. To reference the This AddIn class, you would typically createan instance of it. You can’t do that here because the Visual Studio Tools forOffice runtime creates an instance of the class when the add-in starts.Instead, use Globals. ThisAddIn to refer to the existing instance.

Thecode above is the programmatic equivalent of making selections in the Printdialog box, as shown in Figure 8,and then clicking OK to print.

Fig 8.JPG

Figure8. The code above makes theseselections.

SelectView | Designer. Double-click thePrint 6 button. Add the following code to the print6Button_Click event handler:

With Globals.ThisAddIn.Application.ActivePresentation
  .PrintOptions.OutputType = _
    PowerPoint.PpPrintOutputType.ppPrintOutputSixSlideHandouts
  .PrintOptions.PrintColorType = _
    PowerPoint.PpPrintColorType.ppPrintPureBlackAndWhite
  .PrintOptions.FrameSlides = Office.MsoTriState.msoTrue
  .PrintOut()
End With

SelectView | Designer. Double-click theSave As PPT button. Add the following code to the saveAsPPTButton_Click eventhandler:

SavePresentation("PPT")

SelectView | Designer. Double-click theSave As PPTX button. Add the following code to the saveAsPPTXButton_Click eventhandler:

SavePresentation("PPTX")

Addthe following method to save the presentation as either a PPT or a PPTX:

Private Sub SavePresentation(ByVal format As String)
  Dim pres As PowerPoint.Presentation
  pres = Globals.ThisAddIn.Application.ActivePresentation
  If pres.Path = String.Empty Then
    ' The file has not been previously saved.
    ' It will be saved in the current folder,
    ' which is the location of the add-in assembly.
    If format = "PPT" Then
      pres.SaveAs(pres.Name, _
        PowerPoint.PpSaveAsFileType.ppSaveAsPresentation)
    ElseIf format = "PPTX" Then
      pres.SaveAs(pres.Name, _
        PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation)
    End If
  Else
    ' The file has been previously saved as a ppt or a pptx.
    Dim presName As String = pres.FullName
    If presName.Contains(".pptx") Then
      presName = presName.Remove(presName.Length - 5)
    Else
      presName = presName.Remove(presName.Length - 4)
    End If
    If format = "PPT" Then
      pres.SaveAs(presName, _
        PowerPoint.PpSaveAsFileType.ppSaveAsPresentation)
    ElseIf format = "PPTX" Then
      pres.SaveAs(presName, _
        PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation)
    End If
  End If
End Sub

Thecode listings above use the PowerPoint object model to automate the stepsinvolved in creating, printing and saving a presentation. If you have automatedPowerPoint in the past, either with VBA or external Automation, most of thecode above is probably familiar to you. Very little of it is new to PowerPoint2007.

Saveyour changes and build the solution. To test these buttons in PowerPoint, pressF5. Open an existing presentation.Click the Print 3 button to print handouts with 3 slides on each page. Clickthe Print 6 button to print handouts with 6 slides on each page. Click the SaveAs PPT button to save a copy of the presentation that is compatible withPowerPoint 97 – 2003. Click the Save As PPTX button to save a copy of thepresentation in PowerPoint 2007 format.

Get the Most Out of the Ribbon

Addingbuttons to the Ribbon is a common scenario and a great way to add functionalityto Office applications. The Ribbon supports a number of additional controls youcan use, including drop-down lists, menus and galleries. In the next fewsections of this tutorial, you will see how to use these controls.

Use a Drop-down List

Thebuttons in a gallery perform actions. In contrast, you would typically use theitems in a drop-down list to make a selection before taking an action. Ratherthan have two buttons for saving the presentation, you can select how you wantit saved from a drop-down list and then click a Save button.

ExitPowerPoint and return to the Ribbon Designer in Visual Studio. From theToolbox, drag a Group control onto the Ribbon to the right of the existinggroup. Set the Label property to CommonTasks 2. From the Toolbox, drag a DropDown control into the new group. Namethe control saveAsDropDown. Set theLabel property to Save as. Click theellipsis associated with the Items property. Click Add to add a new item. Set the Label property of the first item to PPT. Click Add to add a new item. Set the Label property of the first item to PPTX. Click OK to close the dialog.

Fromthe Toolbox, drag a Button control into the Common Tasks 2 group. The buttonappears under the drop-down list. Set the ControlSize property to RibbonControlSizeLarge and the buttonmoves to the right of the drop-down list. Name the button saveButton. Set the Label property to Save, the SuperTip property to Savethis presentation and the OfficeImageId property to FileSaveAsOtherFormats.

Double-clickthe Save button. Add the following code to the saveButton_Click event handler:

SavePresentation(saveAsDropDown.SelectedItem.Label)

Saveyour changes and build the solution. To see what this looks like in PowerPoint,press F5. The Common Tasks 2 groupis added to the Add-Ins tab on the Ribbon (see Figure 9).

Fig 9.JPG

Figure9. Use a drop-down list to present theuser with choices.

Use a Menu

Buttonsare the most visual way to display choices in the Ribbon, but they can alsotake up the most screen real estate. One way to save space is to use a menu. ARibbon menu is actually a drop-down list and can contain buttons, check boxes,galleries, other menus, seperators, split buttons and toggle buttons.

ExitPowerPoint and return to the Ribbon Designer in Visual Studio. From theToolbox, drag a Group control onto the Ribbon to the right of the existinggroup. Set the Label property to CommonTasks 3. From the Toolbox, drag a Menu control into the new group. Set theLabel property to Tasks. Click thedown arrow in the menu control to display the menu design surface (see Figure 10).

Fig 10.JPG

Figure10. Add menu items to the menu designsurface.

Fromthe Toolbox, drag a button into the menu design surface. Name the button newUrbanButton. Set the Label propertyto New deck using Urban theme.Double-click the button. Add the following code to the newUrbanButton_Clickevent handler:

With Globals.ThisAddIn.Application
  .Presentations.Add(Office.MsoTriState.msoTrue)
  .ActiveWindow.View.GotoSlide( _
    .ActivePresentation.Slides.Add(Index:=1, _
    Layout:=PowerPoint.PpSlideLayout.ppLayoutTitle).SlideIndex)
  .ActivePresentation.ApplyTemplate( _
    "C:\Program Files\Microsoft Office\" & _
    "Document Themes 12\Urban.thmx")
  If CBool(.ActivePresentation.HasTitleMaster) Then
    With .ActivePresentation.TitleMaster.HeadersFooters
      .Footer.Visible = Office.MsoTriState.msoTrue
      .SlideNumber.Visible = Office.MsoTriState.msoTrue
    End With
  End If
  With .ActivePresentation.SlideMaster.HeadersFooters
    .Footer.Visible = Office.MsoTriState.msoTrue
    .SlideNumber.Visible = Office.MsoTriState.msoTrue
  End With
  With .ActivePresentation.Slides.Range.HeadersFooters
    .Footer.Visible = Office.MsoTriState.msoTrue
    .SlideNumber.Visible = Office.MsoTriState.msoTrue
  End With
  .ActiveWindow.View.GotoSlide( _
    .ActivePresentation.Slides.Add(Index:=2, _
    Layout:=PowerPoint.PpSlideLayout.ppLayoutText).SlideIndex)
  .ActiveWindow.View.GotoSlide( _
    .ActivePresentation.Slides.Add(Index:=2, _
    Layout:=PowerPoint.PpSlideLayout.ppLayoutText).SlideIndex)
  .ActiveWindow.View.GotoSlide(Index:=1)
End With

Thiscode first adds a new presentation. It then adds a title slide and sets thetemplate for the presentation to Urban. The code uses the default installationfolder for Office 2007 themes. The code then turns adds slide numbers to thefooter of each slide. Finally, the code adds two content slides.

SelectView | Designer. From the Toolbox,drag a menu into the menu design surface below the button. Set the Labelproperty to Print Handouts and theOfficeImageId property to FilePrint.Click the right arrow in the menu control to display the menu design surface.Here you will add the menu items that appear when you click Print.

Fromthe Toolbox, drag two buttons into the menu design surface. Name the firstbutton print3FromMenuButton. Set theLabel property to 3 slides per page.Name the second button print6FromMenuButton.Set the Label property to 6 slides perpage. The menu designer should look like Figure 11.Click the left arrow to return to the main menu designer.

Fig 11.JPG

Figure 11. The menu designer should look like this.

Double-clickthe 3 slides per page button. Either copy the code from the print3Button_Clickmethod or move that code into a method and call the method from both theprint3Button_Click and print3FromMenuButton_Click methods.

SelectView | Designer. Double-click the 6slides per page button. Either copy the code from the print6Button_Click methodor move that code into a method and call the method from both theprint6Button_Click and print6FromMenuButton_Click method.

SelectView | Designer. From the Toolbox,drag a menu into the menu design surface below the Print handouts button. Youmay find it easiest to click the up arrow next to Tasks first and then clickthe down arrow to reenter the menu design surface. Set the Label property to Save presentation and the OfficeImageIdproperty to FileSave. Click theright arrow in the menu control to display the menu design surface.

Fromthe Toolbox, drag two buttons into the menu design surface. Name the firstbutton saveAsPPTFromMenuButton. Setthe Label property to Save as PPT. Name the second button saveAsPPTXFromMenuButton. Set the Label property to Save as PPTX.

Double-clickthe Save As PPT button. Add the following code to thesaveAsPPTFromMenuButton_Click event handler:

SavePresentation("PPT")

SelectView | Designer. Double-click theSave As PPTX button. Add the following code to thesaveAsPPTXFromMenuButton_Click event handler:

SavePresentation("PPTX")

Saveyour changes and build the solution. To see what this looks like in PowerPoint,press F5. The Common Tasks 3 groupis added to the Add-Ins tab on the Ribbon (see Figure 12).

Fig 12.JPG

Figure 12. Use a menu to present the userwith choices.

SelectNew deck using Urban theme.PowerPoint creates a new presentation using the Urban theme. Test the two printand save menu items and confirm they behave as expected.

Use a Gallery

Thegallery control is similar to a menu, in that it is a drop-down list thatcontains other controls. A primary difference between a gallery and a menu isthat a gallery can only contain buttons.

ExitPowerPoint and return to the Ribbon Designer in Visual Studio. From theToolbox, drag a Gallery control into CommonTasks 3 group. Set the ControlSize property to RibbonControlSizeLarge, the Label property to Print handouts and the OfficeImageId property to FilePrint.

Clickthe ellipsis associated with the Items property. Click Add to add a new item. Set the Label property of the item to 3 per page, the SuperTip property to Print handouts with 3 slides per pageand the OfficeImageId property to FilePrintQuick.

ClickAdd to add a second item. Set theLabel property of the item to 6 per page,the SuperTip property to Print handoutswith 6 slides per page and the OfficeImageId property to FilePrintQuick. Click OK to close the dialog.

Double-clickthe gallery control. Add the following code to the Gallery1_Click eventhandler:

If CType(CType(sender, RibbonGallery).SelectedItem,  _
  RibbonDropDownItem).Label = "3 per page" Then
  Print3()
Else
  Print6()
End If

Inthis code, sender represents the gallery. To know which button was clicked inthe gallery, the code casts the SelectedItem to a RibbonDropDownItem toretrieve the Label property.

Saveyour changes and build the solution. To see what this looks like in PowerPoint,press F5. The Common Tasks 3 groupis added to the Add-Ins tab on the Ribbon (see Figure 13). Test the two print gallery buttons andconfirm they behave as expected.

Fig 13.JPG

Figure 13. Use agallery to present the user with choices.

Conclusion

In this tutorial, you saw how a variety ofways you can customize the Ribbon in an Office application and add to itshortcuts to perform common tasks. In your daily life, there are a number oftasks you perform over and over, whether you are printing, saving, formatting,etc. By adding controls to the Ribbon, you can now perform these tasks in ahandful of mouse clicks.

Once you learn the object models of thevarious Office applications, you can easily create Ribbon customizations inVisual Studio that can save you time and effort.

AboutRobert Green

Robert Green is a Senior Consultant withMCW Technologies. He is a Microsoft MVP for Visual Studio Tools for Office.Robert has written or co-authored AppDev’s Visual Studio, LINQ, WindowsCommunication Foundation and Windows Workflow Foundation courseware, andappears in the video training for these courses, as well. Robert is a member ofthe INETA Speaker Bureau and has been a frequent speaker at technologyconferences. Before joining MCW, Robert worked at Microsoft for 8 years, as aProgram Manager on the Visual Basic product team and as a Product Manager forVisual Studio, Visual Basic, Visual Studio Tools for Office and Visual FoxPro.