Working with the Microsoft Office Object Models

2,127 views

Published on

Learn how unmanaged objects work in a managed code environment and discover how to control some of the most commonly used Excel, Word, and PowerPoint objects through code.

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,127
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
36
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • CommandBar supports other types, but these are the only ones you can create from code
  • Working with the Microsoft Office Object Models

    1. 1. Working with the Microsoft OfficeObject Models Copyright © by Application Developers Training Company
    2. 2. Objectives• Learn how unmanaged objects work in a managed code environment• Find out about the hierarchical object models that Office products use• Learn how to respond to events in your Office- based solutions• Discover how to control some of the most commonly used Excel, Word, and PowerPoint objects through code• Find out how to add and change command bars in Microsoft Office 2003 products Copyright © by Application Developers Training Company
    3. 3. Agenda• COM Objects in a Managed Code Environment• Working with Properties, Methods, and Member Objects• Responding to Events• Using Word Objects• Working with Excel Objects• Microsoft PowerPoint Objects• Building Command Bars in Office 2003 Copyright © by Application Developers Training Company
    4. 4. COM Objects in a Managed CodeEnvironment• The Office object models are huge• The more proficient you are as an Office user, the better youll be at creating Office solutions• All the Office object models  Are hierarchical  Start with the Application object• Remember that theyre also all COM, not .NET  You get to the object models through the PIAs  The transition from COM to .NET isnt always seamless Copyright © by Application Developers Training Company
    5. 5. Starting at the Top: The ApplicationObject• The products well use here all start with an Application object• Use it to get to everything else• VSTO 2005 SE solutions  Template does the plumbing  Application object is already there because the application launches before your code runs  The templates all define an Application variable for you Copyright © by Application Developers Training Company
    6. 6. Requirements for Automation Solutions• Set a reference to the PIA you need• Declare a variable to hold the Application instance• (Optionally import the namespace to make coding easier to type/read)• Write code to launch the Office product Private app As Word.Application . . . app = New Word.Application Copyright © by Application Developers Training Company
    7. 7. Agenda• COM Objects in a Managed Code Environment• Working with Properties, Methods, and Member Objects• Responding to Events• Using Word Objects• Working with Excel Objects• Microsoft PowerPoint Objects• Building Command Bars in Office 2003 Copyright © by Application Developers Training Company
    8. 8. Working with Properties, Methods, andMember Objects• Properties affect the way the object looks or acts• Methods allow you to do something with the object• Member objects  Are really properties  Return other objects  Used to organize objects into a hierarchy Copyright © by Application Developers Training Company
    9. 9. Properties• Programmatic way for you to change what the user would change through the UI app.ActiveDocument.Paragraphs(1).Bold = True app.Range("A1:B12").Borders.LineStyle = _ XlLineStyle.xlDouble Copyright © by Application Developers Training Company
    10. 10. Methods• Programmatic way for you to do something end users would do through the UI appExcel.Quit appExcel.Range("A1:B12").PrintOut appWord.Quit SaveChanges:=wdSaveChanges, _ OriginalFormat:=wdPromptUser, RouteDocument:=True Copyright © by Application Developers Training Company
    11. 11. Member ObjectsApplication Documents Document Range Paragraphs Paragraph Range Copyright © by Application Developers Training Company
    12. 12. Agenda• COM Objects in a Managed Code Environment• Working with Properties, Methods, and Member Objects• Responding to Events• Using Word Objects• Working with Excel Objects• Microsoft PowerPoint Objects• Building Command Bars in Office 2003 Copyright © by Application Developers Training Company
    13. 13. Responding to Events• In Office, events usually happen in response to user action• Use an event handler to code a response to an event• Event handlers for some objects are available in the templates automatically  Document/Workbook Open events  ItemSend event• In VB, use the WithEvents keyword to expose other events Copyright © by Application Developers Training Company
    14. 14. Agenda• COM Objects in a Managed Code Environment• Working with Properties, Methods, and Member Objects• Responding to Events• Using Word Objects• Working with Excel Objects• Microsoft PowerPoint Objects• Building Command Bars in Office 2003 Copyright © by Application Developers Training Company
    15. 15. The Word Object ModelApplication Documents Document Range Paragraphs Paragraph Range Copyright © by Application Developers Training Company
    16. 16. Using Word Objects• Largest object model in Office• Documents  You can get a reference to any open document using its name or index with the Documents collection Dim doc As Word.Document = _ Application.Documents("Customer.doc")  Two special Document objects o ActiveDocument (member of Application) o ThisDocument (member of Globals class) Copyright © by Application Developers Training Company
    17. 17. Finding Out What’s Active• ActiveDocument tells you which document is active• ThisDocument (in document-level solutions) tells you which document contains the code thats running• Selection tells you where the cursor is in the document Copyright © by Application Developers Training Company
    18. 18. Working with Ranges• Most of the time, you can (and should) use a Range object instead of the Selection object  Doesnt change location of the cursor  Easier to work with text relative to the cursor position (paragraph before/after)• Lots of objects have a Range property  Document  Selection  Bookmark  Footnote  Paragraph, Sentence, Word, etc. Copyright © by Application Developers Training Company
    19. 19. Working with Ranges Entire DocumentActiveDocument.RangeActiveDocument.Range(0,50) Start to character 50ActiveDocument.Paragraphs(3).Range Third paragraph Copyright © by Application Developers Training Company
    20. 20. Inserting Text• Use the Text property of the Range to change text Dim rng As Word.Range = _ Application.ActiveDocument.Range rng.Text = "Text has been inserted!" Copyright © by Application Developers Training Company
    21. 21. Inserting Text• Collapse method  Changes a Range object so it refers to an insertion point at the beginning or end of the starting range  Arguments: wdCollapseStart or wdCollapseEnd Hello Hello rng rng.Collapse Word.WdCollapseDirection.wdCollapseEnd Copyright © by Application Developers Training Company
    22. 22. Inserting Text• The Insert methods  Insert text before or after a range  Insert paragraph markers  Insert cross references  Insert dates• Some replace range, others append to and extend range• Best practice: Collapse range first and then use InsertBefore or InsertAfter Copyright © by Application Developers Training Company
    23. 23. Agenda• COM Objects in a Managed Code Environment• Working with Properties, Methods, and Member Objects• Responding to Events• Using Word Objects• Working with Excel Objects• Microsoft PowerPoint Objects• Building Command Bars in Office 2003 Copyright © by Application Developers Training Company
    24. 24. Working with Excel Objects WorkbooksApplication Workbook Sheets Worksheet WorkSheets Charts ChartObjects Chart Copyright © by Application Developers Training Company Ch
    25. 25. ActiveWorkbook and ThisWorkbook• ActiveWorkbook  The one the cursor is in  Member of the Application object• ThisWorkbook  The one the code is in  Member of the Globals class in a document-level solution  Like ThisDocument, doesnt apply to application-level solutions Copyright © by Application Developers Training Company
    26. 26. ActiveSheet• Whatever sheet the cursor is in• Like the items in the Sheets collect, could be worksheet or chart (or dialog/macro sheet)• Need to cast to a Worksheet or Chart type  Required for C# or VB with Option Strict On  Handy even with Option Strict Off for IntelliSense Dim wks As Excel.Worksheet = _ DirectCast(Application.ActiveSheet, Excel.Worksheet) Dim cht As Excel.Chart = _ DirectCast(Application.ActiveSheet, Excel.Chart) Copyright © by Application Developers Training Company
    27. 27. Casting in Visual Basic• CType  Takes care of any valid conversions for you SalesChart = _ CType(Application.ActiveSheet,_ Excel.Chart)• DirectCast  A little faster than CType if youre sure the object can be cast to the specified type SalesChart = _ DirectCast(Application.ActiveSheet,_ Excel.Chart) Copyright © by Application Developers Training Company
    28. 28. Casting in Visual Basic • TryCast  Sets variable to Nothing if cast cant be doneDim cht As Excel.Chart = _ TryCast(Application.ActiveSheet, _ Excel.Chart)If cht IsNot Nothing Then… Copyright © by Application Developers Training Company
    29. 29. ActiveCell and Selection• ActiveCell is a single-cell range• Selection might be  A multi-cell range  An item in a chart Copyright © by Application Developers Training Company
    30. 30. Using Excel Ranges• Refers to a cell or group of cells  Can refer to a single cell Worksheets(1).Range("A1")  Can refer to multiple cells Worksheets(1).Range("A1:B5")  Can refer to the corners of a range Worksheets(1).Range("A1","B5")  Can refer to a named range Worksheets(1).Range("SalesData") Copyright © by Application Developers Training Company
    31. 31. CurrentRegion• Property of a range• Returns a Range object bounded by empty row and empty column• Tells you how much of the area around the cell is filled in Copyright © by Application Developers Training Company
    32. 32. The Item Property• Default property of a Range object• Refers to specific cell within a Range by row and column coordinates• Coordinates are relative to Range, not worksheet• Use Cells property of worksheet to specify item relative to the worksheet Copyright © by Application Developers Training Company
    33. 33. Working with a Sub-Range• Use Columns or Rows property to find out how wide or long a range is• Build the sub-range from ranges of starting and ending pointsDim rng As Excel.Range = Application.Range(rngStart, rngEnd) Copyright © by Application Developers Training Company
    34. 34. Excel’s Chart Object Worksheet Workbook ChartObjects Chart ChartObject Chart Copyright © by Application Developers Training Company
    35. 35. Creating Excel Charts• Could create a chart in one line of code with the ChartWizard method• Unless youre very familiar with charts, just record it  In Excel, turn on the macro recorder  Create the chart you want  Edit the resulting VBA code to be more efficient/generic/robust  Copy into your Visual Studio project and fix any code that doesnt translate Copyright © by Application Developers Training Company
    36. 36. Agenda• COM Objects in a Managed Code Environment• Working with Properties, Methods, and Member Objects• Responding to Events• Using Word Objects• Working with Excel Objects• Microsoft PowerPoint Objects• Building Command Bars in Office 2003 Copyright © by Application Developers Training Company
    37. 37. Microsoft PowerPoint Objects PresentationsApplication Presentation Slides Slide Shapes TextFrame Shape HasText TextRange Copyright © by Application Developers Training Company
    38. 38. Creating Slides • The Slides.Add method has two required arguments  Index: Location of the new slide within the presentation  Layout: A member of the PpSlideLayout enumerationDim sld As PowerPoint.Slide = _ pres.Slides.Add(pres.Slides.Count + 1, _ PowerPoint.PpSlideLayout.ppLayoutText) Copyright © by Application Developers Training Company
    39. 39. Using the Shape Object• Everything you put on a slide is a Shape  Text box  AutoShape  OLE object  Etc.• Exact properties supported depend on type of shape• Unless you use the layout ppLayoutBlank, every slide you add has one or more shapes on it by default Copyright © by Application Developers Training Company
    40. 40. Finding the Text Property• Many shapes support text, but not all• You need to check for a Text Frame before trying to add text• Use the HasTextFrame propertyDim shp As PowerPoint.Shapeshp = sld.Shapes(1)If shp.HasTextFrame = _ Office.MsoTriState.msoTrue Then… Copyright © by Application Developers Training Company
    41. 41. Finding the Text Property• Once you know shape has a text frame, use it to get at the shapes TextRange property• TextRange object is similar to Words Range object Dim trng As PowerPoint.TextRange trng = shp.TextFrame.TextRange trng.Text = "This is an example" Copyright © by Application Developers Training Company
    42. 42. Finding the Text Property• Change text directly with Text property• Add text before or after existing text with InsertBefore or InsertAfter methods• Other Insert methods include  InsertDateTime  InsertSlideNumber  InsertSymbol Copyright © by Application Developers Training Company
    43. 43. Agenda• COM Objects in a Managed Code Environment• Working with Properties, Methods, and Member Objects• Responding to Events• Using Word Objects• Working with Excel Objects• Microsoft PowerPoint Objects• Building Command Bars in Office 2003 Copyright © by Application Developers Training Company
    44. 44. Building Command Bars in Office 2003• Both document-level and application-level solutions for Office 2003 often include custom menu items and toolbars• To add/change menus and toolbars, you use Offices CommandBars object model  In VSTO 2005 SE, part of Microsoft.Office.Core namespace  CommandBars object model is still supported in Office 2007 Copyright © by Application Developers Training Company
    45. 45. Creating Command Bars• Can reference and customize existing command barsDim cbr As Office.CommandBar = _ Application.CommandBars("Standard")• Can create your own command bar  If you mark it as Temporary, the command bar will be deleted when host app closesDim cbr As Office.CommandBar = _ Application.CommandBars.Add( _ "New Example", Temporary:=True) Copyright © by Application Developers Training Company
    46. 46. Creating Command Bar Controls• Controls can be one of several types  Button  Edit  Dropdown  ComboBox  Popup• Each control type supports properties• Common properties include  Caption  TooltipText  OnAction Copyright © by Application Developers Training Company
    47. 47. Creating Command Bar Controls• In VBA, you use the OnAction property to specify which VBA procedure to run when an event (like a button click) occurs• In VSTO 2005 SE, you need to use a procedure that complies with the events delegateDelegate Sub _ _CommandBarButtonEvents_ClickEventHandler _ (Ctrl As Microsoft.Office.Core.CommandBarButton, _ ByRef CancelDefault As Boolean) Copyright © by Application Developers Training Company
    48. 48. Creating Command Bar Controls• To link the command bar controls event to its handler, use the AddHandler statement AddHandler ctl.Click, _ AddressOf NewControl_Click• Alternatively, use the WithEvents keyword when you declare the control variable and let Visual Studio hook the control and event handler together Copyright © by Application Developers Training Company
    49. 49. Command Bars in Office 2007• Command bars are supported by Office 2007• Microsoft recommends you use them only for backward compatibility• All custom command bars, as well as controls added to built-in command bars, are grouped together in an Add-Ins tab on the ribbon Copyright © by Application Developers Training Company

    ×