working with the microsoft office object models

49
Copyright © by Application Developers Training Company Working with the Working with the Microsoft Office Object Microsoft Office Object Models Models

Upload: learnnowonline

Post on 18-Dec-2014

748 views

Category:

Technology


3 download

DESCRIPTION

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.

TRANSCRIPT

Page 1: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Working with the Microsoft Working with the Microsoft Office Object ModelsOffice Object Models

Page 2: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

ObjectivesObjectives• 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

Page 3: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

AgendaAgenda• 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

Page 4: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

COM Objects in a Managed Code COM Objects in a Managed Code EnvironmentEnvironment• The Office object models are huge• The more proficient you are as an Office user,

the better you'll be at creating Office solutions• All the Office object models

Are hierarchical Start with the Application object

• Remember that they're also all COM, not .NET You get to the object models through the PIAs The transition from COM to .NET isn't always

seamless

Page 5: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Starting at the Top: The Application Starting at the Top: The Application ObjectObject• The products we'll 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

Page 6: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Requirements for Automation Requirements for Automation SolutionsSolutions• 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

Page 7: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

AgendaAgenda• 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

Page 8: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Working with Properties, Methods, Working with Properties, Methods, and Member Objectsand Member 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

Page 9: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

PropertiesProperties• 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

Page 10: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

MethodsMethods• Programmatic way for you to do

something end users would do through the UIappExcel.Quit

appExcel.Range("A1:B12").PrintOut

appWord.Quit SaveChanges:=wdSaveChanges, _ OriginalFormat:=wdPromptUser, RouteDocument:=True

Page 11: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Member ObjectsMember ObjectsApplication

Documents

Document

Paragraphs

Paragraph

Range

Range

Page 12: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

AgendaAgenda• 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

Page 13: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Responding to EventsResponding 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

Page 14: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

AgendaAgenda• 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

Page 15: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

The Word Object ModelThe Word Object ModelApplication

Documents

Document

Paragraphs

Paragraph

Range

Range

Page 16: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Using Word ObjectsUsing 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

Two special Document objectso ActiveDocument (member of Application)o ThisDocument (member of Globals class)

Dim doc As Word.Document = _ Application.Documents("Customer.doc")

Page 17: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Finding Out What’s ActiveFinding Out What’s Active• ActiveDocument tells you which document

is active• ThisDocument (in document-level

solutions) tells you which document contains the code that's running

• Selection tells you where the cursor is in the document

Page 18: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Working with RangesWorking with Ranges• Most of the time, you can (and should)

use a Range object instead of the Selection object Doesn't 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.

Page 19: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Working with RangesWorking with Ranges

ActiveDocument.Range(0,50) Start to character 50

ActiveDocument.RangeEntire Document

ActiveDocument.Paragraphs(3).Range

Third paragraph

Page 20: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Inserting TextInserting Text• Use the Text property of the Range to

change text

Dim rng As Word.Range = _ Application.ActiveDocument.Rangerng.Text = "Text has been inserted!"

Page 21: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Inserting TextInserting 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

rng

Hello

rng.Collapse Word.WdCollapseDirection.wdCollapseEnd

Page 22: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Inserting TextInserting 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

Page 23: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

AgendaAgenda• 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

Page 24: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Working with Excel ObjectsWorking with Excel ObjectsApplication

Workbooks

Workbook

Sheets

Charts

WorkSheets

Worksheet

ChartObjects

Chart

Chart

Page 25: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

ActiveWorkbook and ActiveWorkbook and ThisWorkbookThisWorkbook• 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, doesn't apply to

application-level solutions

Page 26: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

ActiveSheetActiveSheet• 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

IntelliSenseDim wks As Excel.Worksheet = _ DirectCast(Application.ActiveSheet, Excel.Worksheet)

Dim cht As Excel.Chart = _ DirectCast(Application.ActiveSheet, Excel.Chart)

Page 27: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Casting in Visual BasicCasting in Visual Basic• CType

Takes care of any valid conversions for you

• DirectCast A little faster than CType if you're sure the object can be cast to the specified type

SalesChart = _ CType(Application.ActiveSheet,_ Excel.Chart)

SalesChart = _ DirectCast(Application.ActiveSheet,_ Excel.Chart)

Page 28: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Casting in Visual BasicCasting in Visual Basic• TryCast

Sets variable to Nothing if cast can't be done

Dim cht As Excel.Chart = _ TryCast(Application.ActiveSheet, _ Excel.Chart)If cht IsNot Nothing Then…

Page 29: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

ActiveCell and SelectionActiveCell and Selection• ActiveCell is a single-cell range• Selection might be

A multi-cell range An item in a chart

Page 30: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Using Excel RangesUsing Excel Ranges• Refers to a cell or group of cells

Can refer to a single cell

Worksheets(1).Range("A1")

Worksheets(1).Range("A1","B5")

Worksheets(1).Range("A1:B5")

Can refer to multiple cells

Can refer to the corners of a range

Can refer to a named range

Worksheets(1).Range("SalesData")

Page 31: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

CurrentRegionCurrentRegion• 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

Page 32: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

The Item PropertyThe 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

Page 33: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Working with a Sub-RangeWorking 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 points

Dim rng As Excel.Range = Application.Range(rngStart, rngEnd)

Page 34: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Excel’s Chart ObjectExcel’s Chart Object

Workbook

Chart

Worksheet

ChartObjects

ChartObject

Chart

Page 35: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Creating Excel ChartsCreating Excel Charts• Could create a chart in one line of code

with the ChartWizard method• Unless you're 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 doesn't translate

Page 36: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

AgendaAgenda• 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

Page 37: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Microsoft PowerPoint ObjectsMicrosoft PowerPoint ObjectsApplication

Presentations

Presentation

Slides

Slide

Shapes

Shape

HasText

TextFrame

TextRange

Page 38: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Creating SlidesCreating Slides• The Slides.Add method has two required

arguments Index: Location of the new slide within the

presentation Layout: A member of the PpSlideLayout

enumeration

Dim sld As PowerPoint.Slide = _ pres.Slides.Add(pres.Slides.Count + 1, _ PowerPoint.PpSlideLayout.ppLayoutText)

Page 39: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Using the Shape ObjectUsing 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

Page 40: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Finding the Text PropertyFinding 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 property

Dim shp As PowerPoint.Shapeshp = sld.Shapes(1)If shp.HasTextFrame = _ Office.MsoTriState.msoTrue Then…

Page 41: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Finding the Text PropertyFinding the Text Property• Once you know shape has a text frame,

use it to get at the shape's TextRange property

• TextRange object is similar to Word's Range object

Dim trng As PowerPoint.TextRangetrng = shp.TextFrame.TextRangetrng.Text = "This is an example"

Page 42: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Finding the Text PropertyFinding 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

Page 43: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

AgendaAgenda• 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

Page 44: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Building Command Bars in Office Building Command Bars in Office 20032003• 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 Office's CommandBars object model In VSTO 2005 SE, part of Microsoft.Office.Core

namespace CommandBars object model is still supported

in Office 2007

Page 45: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Creating Command BarsCreating Command Bars• Can reference and customize existing

command bars

Dim 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 closes

Dim cbr As Office.CommandBar = _ Application.CommandBars.Add( _ "New Example", Temporary:=True)

Page 46: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Creating Command Bar Creating Command Bar ControlsControls• Controls can be one of several types

Button Edit Dropdown ComboBox Popup

• Each control type supports properties• Common properties include

Caption TooltipText OnAction

Page 47: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Creating Command Bar Creating Command Bar ControlsControls• 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 event's delegate

Delegate Sub _ _CommandBarButtonEvents_ClickEventHandler _ (Ctrl As Microsoft.Office.Core.CommandBarButton, _ ByRef CancelDefault As Boolean)

Page 48: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Creating Command Bar Creating Command Bar ControlsControls• To link the command bar control's 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

Page 49: Working with the Microsoft Office Object Models

Copyright © by Application Developers Training Company

Command Bars in Office 2007Command 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