SlideShare a Scribd company logo
1 of 49
Working with the Microsoft Office
Object Models




   Copyright © by Application Developers Training Company
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
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
COM Objects in a Managed Code
Environment
•   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

       Copyright © by Application Developers Training Company
Starting at the Top: The Application
Object
•   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



       Copyright © by Application Developers Training Company
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
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
Working with Properties, Methods, and
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



       Copyright © by Application Developers Training Company
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
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
Member Objects
Application

           Documents




                       Document
                                                 Range




                                    Paragraphs



                                                    Paragraph
                                                                Range




       Copyright © by Application Developers Training Company
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
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
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
The Word Object Model
Application

           Documents




                       Document
                                                 Range




                                    Paragraphs



                                                    Paragraph
                                                                Range




       Copyright © by Application Developers Training Company
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
Finding 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




       Copyright © by Application Developers Training Company
Working 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.

        Copyright © by Application Developers Training Company
Working with Ranges

                                            Entire Document
ActiveDocument.Range

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


ActiveDocument.Paragraphs(3).Range

                                                    Third paragraph




   Copyright © by Application Developers Training Company
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
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
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
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
Working with Excel Objects

           Workbooks
Application




                       Workbook


                                  Sheets




                                                        Worksheet
                                           WorkSheets
                       Charts




                                                                        ChartObjects
                                                               Chart




       Copyright © by Application Developers Training Company
                                                                       Ch
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, doesn't apply to application-level
      solutions



      Copyright © by Application Developers Training Company
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
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 you're sure the object can be cast to the specified type




    SalesChart = _
     DirectCast(Application.ActiveSheet,_
     Excel.Chart)
            Copyright © by Application Developers Training Company
Casting 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…




        Copyright © by Application Developers Training Company
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
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
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
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
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 points




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



         Copyright © by Application Developers Training Company
Excel’s Chart Object




                                                                 Worksheet
  Workbook




                                                  ChartObjects
 Chart




                                    ChartObject
                            Chart




         Copyright © by Application Developers Training Company
Creating 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


       Copyright © by Application Developers Training Company
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
Microsoft PowerPoint Objects
        Presentations
Application



                        Presentation
                              Slides
                                       Slide
                                               Shapes




                                                                TextFrame
                                                        Shape


                                                                 HasText
                                                                 TextRange

       Copyright © by Application Developers Training Company
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 enumeration


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



       Copyright © by Application Developers Training Company
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
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 property


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



       Copyright © by Application Developers Training Company
Finding 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.TextRange
    trng = shp.TextFrame.TextRange
    trng.Text = "This is an example"




       Copyright © by Application Developers Training Company
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
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
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
    Office's 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
Creating 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)
      Copyright © by Application Developers Training Company
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
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 event's delegate

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




      Copyright © by Application Developers Training Company
Creating Command Bar Controls
•    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




         Copyright © by Application Developers Training Company
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

More Related Content

Viewers also liked

JMP106 “Kum Bah Yah” Meets “Lets Kick Butt” : The Integration of IBM Lotus No...
JMP106 “Kum Bah Yah” Meets “Lets Kick Butt” : The Integration of IBM Lotus No...JMP106 “Kum Bah Yah” Meets “Lets Kick Butt” : The Integration of IBM Lotus No...
JMP106 “Kum Bah Yah” Meets “Lets Kick Butt” : The Integration of IBM Lotus No...John Head
 
Intro to Excel VBA Programming
Intro to Excel VBA ProgrammingIntro to Excel VBA Programming
Intro to Excel VBA Programmingiveytechnologyclub
 
Online Advance Excel & VBA Training in India
 Online Advance Excel & VBA Training in India Online Advance Excel & VBA Training in India
Online Advance Excel & VBA Training in Indiaibinstitute0
 
Why Is Excel VBA So Important For Banks ?
Why Is Excel VBA So Important For Banks ?Why Is Excel VBA So Important For Banks ?
Why Is Excel VBA So Important For Banks ?Jack Tellington
 

Viewers also liked (6)

Sql Server 2014 Course Content
Sql Server 2014 Course ContentSql Server 2014 Course Content
Sql Server 2014 Course Content
 
JMP106 “Kum Bah Yah” Meets “Lets Kick Butt” : The Integration of IBM Lotus No...
JMP106 “Kum Bah Yah” Meets “Lets Kick Butt” : The Integration of IBM Lotus No...JMP106 “Kum Bah Yah” Meets “Lets Kick Butt” : The Integration of IBM Lotus No...
JMP106 “Kum Bah Yah” Meets “Lets Kick Butt” : The Integration of IBM Lotus No...
 
Intro to Excel VBA Programming
Intro to Excel VBA ProgrammingIntro to Excel VBA Programming
Intro to Excel VBA Programming
 
Vba part 1
Vba part 1Vba part 1
Vba part 1
 
Online Advance Excel & VBA Training in India
 Online Advance Excel & VBA Training in India Online Advance Excel & VBA Training in India
Online Advance Excel & VBA Training in India
 
Why Is Excel VBA So Important For Banks ?
Why Is Excel VBA So Important For Banks ?Why Is Excel VBA So Important For Banks ?
Why Is Excel VBA So Important For Banks ?
 

Similar to Working with the Microsoft Office Object Models

AD303: Building Composite Applications for IBM Workplace Collaboration Servic...
AD303: Building Composite Applications for IBM Workplace Collaboration Servic...AD303: Building Composite Applications for IBM Workplace Collaboration Servic...
AD303: Building Composite Applications for IBM Workplace Collaboration Servic...Brian O'Gorman
 
Building iOS App Project & Architecture
Building iOS App Project & ArchitectureBuilding iOS App Project & Architecture
Building iOS App Project & ArchitectureMassimo Oliviero
 
Customizing ERModernLook Applications
Customizing ERModernLook ApplicationsCustomizing ERModernLook Applications
Customizing ERModernLook ApplicationsWO Community
 
building an app exchange app
building an app exchange appbuilding an app exchange app
building an app exchange appvraopolisetti
 
Dev day paris020415
Dev day paris020415Dev day paris020415
Dev day paris020415pdufourSFDC
 
Sviluppare app per office
Sviluppare app per officeSviluppare app per office
Sviluppare app per officeFabio Franzini
 
An introduction to microsoft power apps
An introduction to microsoft power appsAn introduction to microsoft power apps
An introduction to microsoft power appsMitul Rana
 
Net, MVC 3+ years Experience
Net, MVC 3+ years ExperienceNet, MVC 3+ years Experience
Net, MVC 3+ years ExperienceMadhava B
 
Chris OBrien - Weaving Enterprise Solutions into Office Products
Chris OBrien - Weaving Enterprise Solutions into Office ProductsChris OBrien - Weaving Enterprise Solutions into Office Products
Chris OBrien - Weaving Enterprise Solutions into Office ProductsChris O'Brien
 
Develop, Build, Package and Deploy Office Add-ins with Visual Studio - ESPC 2015
Develop, Build, Package and Deploy Office Add-ins with Visual Studio - ESPC 2015Develop, Build, Package and Deploy Office Add-ins with Visual Studio - ESPC 2015
Develop, Build, Package and Deploy Office Add-ins with Visual Studio - ESPC 2015Bram de Jager
 
Introduction To Angular.js - SpringPeople
Introduction To Angular.js - SpringPeopleIntroduction To Angular.js - SpringPeople
Introduction To Angular.js - SpringPeopleSpringPeople
 

Similar to Working with the Microsoft Office Object Models (20)

AD303: Building Composite Applications for IBM Workplace Collaboration Servic...
AD303: Building Composite Applications for IBM Workplace Collaboration Servic...AD303: Building Composite Applications for IBM Workplace Collaboration Servic...
AD303: Building Composite Applications for IBM Workplace Collaboration Servic...
 
Building iOS App Project & Architecture
Building iOS App Project & ArchitectureBuilding iOS App Project & Architecture
Building iOS App Project & Architecture
 
VSTO
VSTOVSTO
VSTO
 
Customizing ERModernLook Applications
Customizing ERModernLook ApplicationsCustomizing ERModernLook Applications
Customizing ERModernLook Applications
 
mahesh new resume sfdc
mahesh new resume sfdcmahesh new resume sfdc
mahesh new resume sfdc
 
building an app exchange app
building an app exchange appbuilding an app exchange app
building an app exchange app
 
Dev day paris020415
Dev day paris020415Dev day paris020415
Dev day paris020415
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Resume
ResumeResume
Resume
 
Sviluppare app per office
Sviluppare app per officeSviluppare app per office
Sviluppare app per office
 
An introduction to microsoft power apps
An introduction to microsoft power appsAn introduction to microsoft power apps
An introduction to microsoft power apps
 
Net, MVC 3+ years Experience
Net, MVC 3+ years ExperienceNet, MVC 3+ years Experience
Net, MVC 3+ years Experience
 
Chris OBrien - Weaving Enterprise Solutions into Office Products
Chris OBrien - Weaving Enterprise Solutions into Office ProductsChris OBrien - Weaving Enterprise Solutions into Office Products
Chris OBrien - Weaving Enterprise Solutions into Office Products
 
Develop, Build, Package and Deploy Office Add-ins with Visual Studio - ESPC 2015
Develop, Build, Package and Deploy Office Add-ins with Visual Studio - ESPC 2015Develop, Build, Package and Deploy Office Add-ins with Visual Studio - ESPC 2015
Develop, Build, Package and Deploy Office Add-ins with Visual Studio - ESPC 2015
 
downloadfile
downloadfiledownloadfile
downloadfile
 
muni resume (1)
muni resume (1)muni resume (1)
muni resume (1)
 
Introduction To Angular.js - SpringPeople
Introduction To Angular.js - SpringPeopleIntroduction To Angular.js - SpringPeople
Introduction To Angular.js - SpringPeople
 
Resume
ResumeResume
Resume
 
Alpana_Srivastava
Alpana_SrivastavaAlpana_Srivastava
Alpana_Srivastava
 
Overview of Capturing requirements
Overview of Capturing requirementsOverview of Capturing requirements
Overview of Capturing requirements
 

More from LearnNowOnline

Windows 8: Shapes and Geometries
Windows 8: Shapes and GeometriesWindows 8: Shapes and Geometries
Windows 8: Shapes and GeometriesLearnNowOnline
 
SQL: Permissions and Data Protection
SQL: Permissions and Data ProtectionSQL: Permissions and Data Protection
SQL: Permissions and Data ProtectionLearnNowOnline
 
New in the Visual Studio 2012 IDE
New in the Visual Studio 2012 IDENew in the Visual Studio 2012 IDE
New in the Visual Studio 2012 IDELearnNowOnline
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingLearnNowOnline
 
Asynchronous Programming
Asynchronous ProgrammingAsynchronous Programming
Asynchronous ProgrammingLearnNowOnline
 
WPF: Working with Data
WPF: Working with DataWPF: Working with Data
WPF: Working with DataLearnNowOnline
 
Object oriented techniques
Object oriented techniquesObject oriented techniques
Object oriented techniquesLearnNowOnline
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptLearnNowOnline
 
SharePoint Document Management
SharePoint Document ManagementSharePoint Document Management
SharePoint Document ManagementLearnNowOnline
 
SharePoint: Introduction to InfoPath
SharePoint: Introduction to InfoPathSharePoint: Introduction to InfoPath
SharePoint: Introduction to InfoPathLearnNowOnline
 
Managing site collections
Managing site collectionsManaging site collections
Managing site collectionsLearnNowOnline
 
What's new in Silverlight 5
What's new in Silverlight 5What's new in Silverlight 5
What's new in Silverlight 5LearnNowOnline
 
KnockOutJS with ASP.NET MVC
KnockOutJS with ASP.NET MVCKnockOutJS with ASP.NET MVC
KnockOutJS with ASP.NET MVCLearnNowOnline
 
Expression Blend Motion & Interaction Design
Expression Blend Motion & Interaction DesignExpression Blend Motion & Interaction Design
Expression Blend Motion & Interaction DesignLearnNowOnline
 

More from LearnNowOnline (20)

Windows 8: Shapes and Geometries
Windows 8: Shapes and GeometriesWindows 8: Shapes and Geometries
Windows 8: Shapes and Geometries
 
SQL: Permissions and Data Protection
SQL: Permissions and Data ProtectionSQL: Permissions and Data Protection
SQL: Permissions and Data Protection
 
New in the Visual Studio 2012 IDE
New in the Visual Studio 2012 IDENew in the Visual Studio 2012 IDE
New in the Visual Studio 2012 IDE
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programming
 
Asynchronous Programming
Asynchronous ProgrammingAsynchronous Programming
Asynchronous Programming
 
WPF: Working with Data
WPF: Working with DataWPF: Working with Data
WPF: Working with Data
 
A tour of SQL Server
A tour of SQL ServerA tour of SQL Server
A tour of SQL Server
 
Introducing LINQ
Introducing LINQIntroducing LINQ
Introducing LINQ
 
Generics
GenericsGenerics
Generics
 
Object oriented techniques
Object oriented techniquesObject oriented techniques
Object oriented techniques
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
SharePoint Document Management
SharePoint Document ManagementSharePoint Document Management
SharePoint Document Management
 
SharePoint: Introduction to InfoPath
SharePoint: Introduction to InfoPathSharePoint: Introduction to InfoPath
SharePoint: Introduction to InfoPath
 
Managing site collections
Managing site collectionsManaging site collections
Managing site collections
 
Web API HTTP Pipeline
Web API HTTP PipelineWeb API HTTP Pipeline
Web API HTTP Pipeline
 
Web API Basics
Web API BasicsWeb API Basics
Web API Basics
 
SQL Server: Security
SQL Server: SecuritySQL Server: Security
SQL Server: Security
 
What's new in Silverlight 5
What's new in Silverlight 5What's new in Silverlight 5
What's new in Silverlight 5
 
KnockOutJS with ASP.NET MVC
KnockOutJS with ASP.NET MVCKnockOutJS with ASP.NET MVC
KnockOutJS with ASP.NET MVC
 
Expression Blend Motion & Interaction Design
Expression Blend Motion & Interaction DesignExpression Blend Motion & Interaction Design
Expression Blend Motion & Interaction Design
 

Recently uploaded

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

Working with the Microsoft Office Object Models

  • 1. Working with the Microsoft Office Object Models Copyright © by Application Developers Training Company
  • 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. 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. COM Objects in a Managed Code Environment • 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 Copyright © by Application Developers Training Company
  • 5. Starting at the Top: The Application Object • 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 Copyright © by Application Developers Training Company
  • 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. 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. Working with Properties, Methods, and 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 Copyright © by Application Developers Training Company
  • 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. 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. Member Objects Application Documents Document Range Paragraphs Paragraph Range Copyright © by Application Developers Training Company
  • 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. 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. 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. The Word Object Model Application Documents Document Range Paragraphs Paragraph Range Copyright © by Application Developers Training Company
  • 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. Finding 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 Copyright © by Application Developers Training Company
  • 18. Working 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. Copyright © by Application Developers Training Company
  • 19. Working with Ranges Entire Document ActiveDocument.Range ActiveDocument.Range(0,50) Start to character 50 ActiveDocument.Paragraphs(3).Range Third paragraph Copyright © by Application Developers Training Company
  • 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. 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. 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. 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. Working with Excel Objects Workbooks Application Workbook Sheets Worksheet WorkSheets Charts ChartObjects Chart Copyright © by Application Developers Training Company Ch
  • 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, doesn't apply to application-level solutions Copyright © by Application Developers Training Company
  • 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. 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 you're sure the object can be cast to the specified type SalesChart = _ DirectCast(Application.ActiveSheet,_ Excel.Chart) Copyright © by Application Developers Training Company
  • 28. Casting 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… Copyright © by Application Developers Training Company
  • 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. 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. 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. 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. 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 points Dim rng As Excel.Range = Application.Range(rngStart, rngEnd) Copyright © by Application Developers Training Company
  • 34. Excel’s Chart Object Worksheet Workbook ChartObjects Chart ChartObject Chart Copyright © by Application Developers Training Company
  • 35. Creating 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 Copyright © by Application Developers Training Company
  • 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. Microsoft PowerPoint Objects Presentations Application Presentation Slides Slide Shapes TextFrame Shape HasText TextRange Copyright © by Application Developers Training Company
  • 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 enumeration Dim sld As PowerPoint.Slide = _ pres.Slides.Add(pres.Slides.Count + 1, _ PowerPoint.PpSlideLayout.ppLayoutText) Copyright © by Application Developers Training Company
  • 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. 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 property Dim shp As PowerPoint.Shape shp = sld.Shapes(1) If shp.HasTextFrame = _ Office.MsoTriState.msoTrue Then… Copyright © by Application Developers Training Company
  • 41. Finding 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.TextRange trng = shp.TextFrame.TextRange trng.Text = "This is an example" Copyright © by Application Developers Training Company
  • 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. 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. 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 Office's 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. Creating 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) Copyright © by Application Developers Training Company
  • 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. 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 event's delegate Delegate Sub _ _CommandBarButtonEvents_ClickEventHandler _ (Ctrl As Microsoft.Office.Core.CommandBarButton, _ ByRef CancelDefault As Boolean) Copyright © by Application Developers Training Company
  • 48. Creating Command Bar Controls • 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 Copyright © by Application Developers Training Company
  • 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

Editor's Notes

  1. CommandBar supports other types, but these are the only ones you can create from code