Using the Actions Pane

You will now convert your sample from showing a modal dialog box to showing an actions pane that will enable the user to update the bookmarks. As described in Chapter 5, the actions pane is docked and does not obstruct users' view of the document as a Windows Form does. This helps the users understand the context of the fields they are adding. Converting a Windows Form to a User Control It is super easy to make this conversion. A user control can be placed in other controls or forms. In the...

Adding Other Controls to the Ribbon

So far you've seen examples that show how to create your own toggle button or use an existing one. You can add a number of other controls to the Ribbon, and you can see a list of them in IntelliSense, as shown in Figure 14.23. Figure 14.22. Custom button added to custom group within built-in tab Ribbonl.Hml* Ribbonl .vb ThisApplication.vb File System (ExcelAddinlSetup) Start Page B < customUI xralns 'rhttp sch mas .microsoft. com of fice 200 6 01 custoraui onLoad OnLoad> < ribbon <...

Using Regular Expressions to Recognize Phrases

As mentioned earlier, you shouldn't add a phrase (multiple words) to the Terms property of a smart tag because the tokens they are matched against contain only one word and thus a match will never be found. One way to have your solution recognize multiple words that are separated by spaces is to add the phrase as a regular expression to the smart tag's Expressions property. In VSTO, there are several objects, such as SmartTags, ListObjects, and ActionsPanes, that are named by concatenating...

Creating and Calling Constructors

As you saw in the example in Listing 3.3, you use the New keyword to create an instance of a class. The New keyword calls the constructor of the class. A class constructor describes how to initialize the properties and methods of the class. Every class has a default constructor that is automatically generated for you as a method called Sub New. You can override this default constructor by adding your own procedure named Sub New. Constructors can take parameters and can also be overloaded so...

Excel Host Items and Host Controls

VSTO enhances a number of objects in the Excel object model, such as the ability to bind data to an object and to expose the object's events. These objects are defined as host items and host controls. Recall that host items are containers for host controls in the same way that a UserForm is a container for an ActiveX control. You add the host controls to the host item. Excel has three types of host items Workbook, Worksheet, and Chartsheet. There is one Workbook host item and a separate...

Adding Data Bound Controls to the Worksheet

By default, each of the fields in the Customers table in the Data Sources window displays a NamedRange control, indicating the type of control that will be added to the worksheet when you drag the field to it. You can change the type of control by clicking the arrow next to ContactName to reveal a drop-down menu, as shown in Figure 7.21. Figure 7.21. Selecting the type of control to data-bind Figure 7.21. Selecting the type of control to data-bind Now you can drag the selected type of control...

Code Access Security

CAS is the security system for the .NET Framework. Although a complete explanation of CAS is outside the scope of this book, we cover a few basic concepts. CAS is different from Windows security, which is a role-based system. Role-based security grants permissions based on the user's role for example, being a member of the administrators group or the power users group. In contrast, CAS grants permissions based on what the code is allowed to do, regardless of the role of the user running the...

Adding Controls at Run Time

Most host controls can be added to the Word document at run time. There are two exceptions to this rule, both of them related to XML mapping. VSTO does not provide a way to add XMLNode and XMLNodes controls to the document programmatically. You can add these controls only when you map an XML element to the document using Word's native functionality at design time. In Chapter 3, you learned that to create an instance of an object you must use the New keyword. This technique is not supported for...

Browsing the Object Browser

The Visual Studio IDE has an Object Browser similar to the one you find in the VBE. You can use the Object Browser to view all the methods, properties, and events of a particular object, as shown in Figure 2.18. For example, you can use the Object Browser to learn about all the extended objects in VSTO. The Object Browser displays all available 'Object Browser ' 5ampleWorkbook.xls 5tart Page Microsoft, Off ice. Tools, Excel 0 Action S BeforeAddDataBoundRowEventArgs_...

Changes to Control Functionality

In addition to changes in the names of the properties, methods, and events, the functionality of the controls might also differ. For example, Windows Forms controls have a different implementation for handling data access and fonts. Using VBA, you can set the font of a control by setting the font properties directly. In Visual Basic 2005, you must create an instance of a System.Drawing.Font object whenever you want to programmatically set the font property of a control. Listing 4.16 shows how...

Converting a Recorded VBA Macro to Visual Basic in VSTO

In this section, you will record a simple macro in VBA, but instead of associating the macro with a toolbar button using the Customize dialog box (as shown in Figure 6.1), you'll convert the code to Visual Basic 2005. You can then add the code to the Click event handler of a toolbar button that you'll create programmatically using VSTO. Figure 6.1. Using the Customize dialog box to associate VBA macros with menu and toolbar items Figure 6.1. Using the Customize dialog box to associate VBA...

Solution Assemblies

As you learned earlier In this chapter, an assembly Is a collection of classes and functionality that is stored as an executable file (.exe) or a library (.dll). When you build a VSTO solution, the code is compiled and stored in a single assembly (DLL file) located in the bin debug (or bin release) directory of your solution. The assembly isn't stored inside the document, but the document does include an application manifest, which contains information about the name and location of the...

Using the Code Snippets Manager

You can use the Code Snippets Manager to add your code snippet to the code snippet folder list. To view the Code Snippets Manager, you can select it from the Tools menu. You select the language category for your code snippet in the Language drop-down, and navigate to the folder where you want to store your snippet. To add a code snippet to an existing folder, click Import, and then select your code snippet. To add a folder to the folder list, click Add and navigate to the folder you want to...

Before DoubleClick

The BeforeDoubleClick event handler enables you to take action when a user double-clicks the document. For a code example, see Listing 6.17, which shows the BeforeDoubleClick event of a Bookmark control. If you add code to the BeforeDoubleClick event handler of both the Document and the Bookmark, both events are raised when a user double-clicks the Bookmark control. If you do not want both events to be handled, you must write code to determine which object has raised the event, and then handle...

Reenabling a Hard Disabled Addin

We use the code in Listing 10.14 to show an example of hard-disabling an Outlook add-in. 1. Add a breakpoint to the line of code that divides the first number by the second number, as shown in Figure 10.16. Figure 10.16. Setting a breakpoint in the Startup event handler of an Outlook add-in Figure 10.16. Setting a breakpoint in the Startup event handler of an Outlook add-in 3. When execution of the code stops at the breakpoint, as shown in Figure 10.17, click the Stop Debugging button. Thi...

The Data Sources Window

The Data Sources window is a new feature in Visual Studio 2005 that helps you create or open data connections and bind data to controls in your solution. For example, you can add a Windows form to your solution and bind a combo box on the form to a data source. In the Data Sources window, you can select the desired control and drag it to a Windows form. Visual Studio adds a data-bound control to the Windows form and displays the data when the form is launched. You can also drag items from the...

Security in Outlook Addins Created with VSTO

The security requirements of Outlook add-ins match those of document-level customizations for Word and Excel created with VSTO. By default VSTO solutions are very secure, using code access security (CAS). Additionally, in order for AddinLoader.dll to load a VSTO add-in, it must have the proper .NET Framework security policies applied. In Chapter 11 you will learn more about security requirements for Outlook add-ins created with VSTO. Outlook 2003 improved its security model through the Outlook...

Sheet Activate Event Handler

The SheetActivate event is raised whenever a worksheet in the workbook is activated. Because each of the VSTO worksheets also has an ActivateEvent event, you write code here to capture the event for any of the worksheets. The code in Listing 7.48 displays the name of the active worksheet, along with its code name, in the status bar. To test this code, change the name of a worksheet, and then deactivate and reactivate it. Listing 7.48. Displaying the active worksheet in the status bar Private...

The Exception Assistant

An exception is an error that occurs when your application is running. The Exception Assistant is a new feature that provides information whenever an unhandled exception occurs at run time. The Exception Assistant displays the location of the coding error and shows tips on how to resolve the issue. To disable the Exception Assistant, select the General tab of the Debugging node in the Options dialog box, and then clear the Enable the Exception Assistant check box. After you disable this option,...

Creating Multiple Actions Pane Controls

To have a dynamic actions pane, you must create multiple controls that you can add and remove according to the user's context in the document. In this section you will create two controls. You can use the default control names for all of the Windows Forms controls that you add to the actions pane controls. 1. Add two actions panes controls to your Word solution, keeping the default names (ActionsPaneControll and ActionsPaneControl2). 2. Add three Label controls to ActionsPaneControll, and set...

Properties Window

Both Visual Studio and the VBE have a Properties window. This window, which displays the properties of the currently selected item in your project, enables you to modify the properties during application design. However, some of the property values do not change until the project is actually running. For example, if you set the Visible property of a Win- Figure 2.16. Add New Item dialog box Figure 2.16. Add New Item dialog box dows Form control to False, the control becomes invisible only when...

Removing the VBA Code and the User Form from the Template

Open the template in Word by clicking Open on the File menu. Then press ALT+F11 to open the VBA Code Editor. 2. In the Forms folder, delete the frmMain form. 3. In the Microsoft Word Objects folder, open the ThisDocument code. Delete all the code by selecting the code with the mouse and pressing the DELETE key. 4. Save the file as Professional Memo VSTO.dot. Now that you have removed all the VBA code, you are ready to use the template to create your VSTO project. 1. Create a new VSTO Word...

Caching Data in the Workbook

A data cache is a place where you can store and retrieve data within a document. VSTO allows you to cache data in an Excel workbook. This feature is useful when you bind data to a document and want to let users update the data while they are not connected to a server that contains the database. VBA developers often use a hidden sheet to store data that they don't want to have visible in the document. Now this data can be stored in the data cache. Cached data is stored in a hidden ActiveX...

Extending Code to Add a Custom Graphic to the Toolbar Button

You can extend this code to add a custom graphic rather than the built-in graphic (faceID 34). To do this, you first create two bitmap files. The first bitmap will contain the graphic you want to use. The second bitmap will contain the same graphic, but with a white background and with the entire foreground set to black. This second bitmap, known as a mask, indicates which area of the original graphic (the background) should be transparent so that it takes on the color of the toolbar. The first...

Call Stack Window

The call stack is a list of all procedures that have executed. The Call Stack window displays the name of every function or procedure that is currently in the stack. The top of the stack is always the current point of execution. To display the Call Stack window, click the Debug menu, point to Windows, and then click Call Stack. By default, Visual Studio hides nonuser code. This hidden code is represented by the text < External Code> . To view this code, right-click the window and select...

Creating an Actions Pane Solution

Usually, you place the code that adds the control to the actions pane in the Startup event handler of either ThisDocument or ThisWorkbook, depending on whether you're working in Word or Excel. This causes the code to add the control to the actions pane so that it is visible when you open the document. You can also add this code to other procedures. For example, you might want to display a control in the Document Actions task pane when a user moves the cursor into a particular area of the...

Creating a User Control

In this section you'll create a user control and then add Windows Forms controls for selecting graphics and entering text. A user control acts as a container for all the Windows Forms controls that you add to it. You Figure 8.11. Adding a table to a header Figure 8.11. Adding a table to a header can then programmatically add the user control to a Windows Form that you'll display when the user clicks the Create button on the Logo menu. Theoretically, you could design a Windows Form simply by...

Programming in Excel

Many solutions developers use Microsoft Excel as a development platform because of its rich environment. You can take advantage of Excel's powerful calculation engine, charting capabilities, customizable task panes, and extensive object model. VSTO enables rapid application development of Excel solutions by enhancing many of Excel's objects, enabling quick development of smart tags and customized actions panes, supporting Windows Forms controls on the worksheet, and providing a robust...

Microsoft Installer Project

Another approach to deploying your VSTO solutions is to use a Visual Studio Setup project. The Visual Studio Setup project creates a Microsoft installer file, which has the extension .msi. The MSI files are standard Microsoft installer files. MSI files display an Install Wizard and add an entry to the Add And Remove Programs feature in the Control Panel to allow you to repair and uninstall the application. Earlier in this chapter you learned about some of the shortcomings of the Publish Wizard,...

What Is a Smart

Smart tags are a Microsoft Office feature that can be programmed to recognize certain text and then present users with actions they can take related to the text. Smart tags implement two interfaces ISmartTagRecognizer (the recognizer) and ISmartTagAction (the action). Microsoft Word and Excel include a number of built-in smart tags. For example, if you type a person's first and last names into a Word document, Word places a red dotted line underneath the name, indicating that a smart tag has...

Create a toolbar and add a button as shown in Listing B

Adding a toolbar and button to the Inspector Private Sub MyInspector_NewInspector(ByVal Inspector As _ _ Handles MyInspector.NewInspector If TypeOf Inspector.CurrentItem Is Outlook.ContactItem Then Try ' Assign CommandBar to variable if it exists. MyCommandBar Catch End Try ' Otherwise re-create it. If MyCommandBar Is Nothing Then MyCommandBar Inspector.CommandBars.Add( _ Name Sample, Temporary True) ' Assign button to variable, if it exists. MyButton Catch End Try ' Otherwise add...

Windows Forms Controls in Word

By default, VSTO adds Word controls to the document inline with text. This means that the control is placed within the text of a document, and, as the text is repositioned, the control also repositions. For example, if you add text to the beginning of a paragraph that contains an inline control, the control will move with the text, or wrap to the next line, when new text is added. You can change an inline control into a floating object. This means that the control is placed in a drawing layer...

User Forms Versus Windows Forms

Vba Windows Forms

When you use VBA to create an Office solution, you can design a user interface to display a dialog box. To do so, you add a UserForm to your project and then add controls to the UserForm. These controls are Figure 4.7. A UserForm in VBA that contains all the default ActiveX controls Figure 4.7. A UserForm in VBA that contains all the default ActiveX controls referred to as ActiveX controls. Whenever the UserForm has focus, the Toolbox, which contains all the default controls, becomes visible....

Using the Actions Pane Object

VSTO provides an ActionsPane object that enables you to customize the task pane with one line of code. You can think of the actions pane as a container for Windows Forms controls. The actions pane sits inside the Document Actions task pane, which is hosted within the Word or Excel task pane. To customize the Document Actions task pane, you simply add controls to the ActionsPane object. You can add a Windows Forms control directly to the actions pane through code. As soon as you add the control,...

Customizing the Document Actions Task Pane

You can customize the task pane In Word and Excel by using Smart Document technology or by using the ActionsPane object in VSTO. After you have customized the task pane, it appears in the list of task panes available and is called the Document Actions task pane. Figure 5.1 shows the Document Actions task pane listed along with the built-in Word task panes. This entry does not appear until after you have written code to customize the task pane, and you cannot change the name of this task pane it...

Converting a Document Level Customization to a Vsto Se Addin

In this section, you'll convert a document-level customization that uses the actions pane to a VSTO 2005 SE add-in that uses the Custom task pane. In Chapter 5, you created an Excel solution that displays a custom-made Styles and Formatting task pane. That solution works only for a particular workbook, so let's convert the solution to a VSTO 2005 SE add-in so that it will work with any workbook that is opened. 1. Create a new Excel 2007 add-in project. 2. Add the user control you created for...

Simple Migration of a Word VBA Project

In this section, you will migrate a sample Word VBA application to VSTO. As shown in Figure 12.1, the application is a simple memo template that prompts users for information when they create a new document. After users enter information into the fields of the VBA UserForm and click OK, the bookmarks on the document are populated with the information. The New event fires when a new document is created from a template. It is here that you will write the code to show the UserForm, because the...

Contents

Foreword xxi Preface xxv Introduction xxvii Acknowledgments xxxiii About the Authors xxxv Chapter 1 Getting Started with VSTO 3 Topics Covered in This Chapter 3 What Is VSTO 3 Why Use VSTO Instead of VBA 5 Features of VSTO 7 Host Items and Host Controls 8 Windows Forms Controls 10 Smart Tags 12 Customizing Task Panes 12 Caching Data in a Document 13 Managed Add-ins 13 Security and Deployment 14 Ribbon Support 15 Enhanced Development Environment 15 Creating VSTO Solutions 15 Creating Office...

This function is called when Outlook is ready to load the form region manifest and it returns the embedded form region

Returning the embedded form region manifest file Public Function GetFormRegionManifest( _ ByVal FormRegionName As String, _ ByVal LCID As Integer) As Object _ Implements ' Read the embedded manifest file out of the assembly. Dim MySimpleFormRegionManifest As String _ Return MySimpleFormRegionManifest 5. Implement GetFormRegionlcon by adding the code in Listing 14.38. This function is called when Outlook is ready to load the form region icon, and it returns the embedded form...

Exploring Solution Explorer

Solution Explorer Excel

Visual Studio projects are displayed and managed in a window called Solution Explorer. Solution Explorer acts as a container for all the items in your solution. For example, the solution might contain multiple projects, and each project might contain multiple items such as code files, Windows forms, or resources. When you create a VSTO solution, Visual Studio automatically creates a project for the solution, along with a default set of associated items. For example, when you create an Excel...

Activate Event Event Handler

You can write code in the ActivateEvent handler of a worksheet to take action whenever a particular worksheet has focus. For example, you can show only one actions pane per workbook, but you can write code to display various controls on the actions pane that are specific to the visible worksheet. Add the code in Listing 7.41 to the Sheet1 class to see an example. Listing 7.41. Showing controls on the actions pane when the ActivateEvent of Sheetl is raised Dim Sheet1Control As New MonthCalendar...

Before DoubleClick Event Handler

When you double-click a cell on a worksheet, the default action is to place Excel in edit mode. If you want to replace this action with another one, you can write code in the BeforeDoubleClick event handler. For example, let's say you want to turn bold formatting on and off whenever a named range is double-clicked. You can add the code in Listing 7.24 to the BeforeDoubleClick event handler of a NamedRange control called NamedRange1. When you run this code, double-click the NamedRange, and then...

Attaching a Solution to a Document Using Server Document

A common attaching scenario involves document processing. In this scenario, you receive an invoice from a customer and need to process it by uploading the data to a database in your company. The customer sends you an Office document, and you then attach an existing VSTO solution to the document. Now the VSTO customization runs whenever you open the document. Or suppose you've created functionality that you want to use on any document. For example, if you have created a customization for...

Creating an Addin for Power Point

Create a new PowerPoint 2007 add-in project. 2. In Solution Explorer, right-click the project, point to Add, and then click User Control. 3. In the New Item dialog box, ensure that User Control is selected, leaving the default name UserControl1, and then click Add. 3. Add a Label control to the user control, and change the text to View. 4. Add a ComboBox control below the label. 5. Double-click the user control, and add the code in Listing 14.23 to the Load event of UserControl1. Private Sub...

Application Level Customizations Using VSTO

If you have ever customized Outlook by using VBA or by creating a COM add-in, then you know that these customizations are application-level. VSTO supports application-level customization for Outlook through managed add-ins. Because Outlook doesn't have documents in the same way that Word and Excel do, it makes sense that the customiza-tions are associated with the entire Outlook application. VSTO provides a type that wraps the Outlook Application object, but it does not add any functionality to...

Writing Code in an Excel Workbook

In this section, you will create a new Excel workbook and add code that contains errors. (The user interface might differ depending on your Visual Studio development settings. The examples in this book assume that you have chosen the Visual Basic development setting.) 1. Create a directory at the root of the C drive, and name it Samples. This is the directory where you can store all the VSTO solutions described in this book. 3. On the File menu, point to New and then click Project. 4. In the...

The My Objects

The new My objects give you easy access to application, system, and user information without having to search through the .NET Framework class libraries to locate equivalent functionality. Instead, if you type My followed by a period, IntelliSense displays all the members of the My objects that are available to VSTO solutions. Table 4.1 describes these objects as well as those that are not available. Table 4.1. The My Objects in Visual Basic 2005 Table 4.1. The My Objects in Visual Basic 2005...

Primary Interop Assemblies

Office applications, such as Word and Excel, are written in unmanaged code. For your VSTO solution (managed code) to interoperate with the unmanaged COM objects in the Office application, it must use an interoperability assembly. Visual Studio can create an interoperability assembly for you when you set a reference to a COM type library, but generating an interoperability assembly in this way is not recommended. Instead, you should use the official interoperability assembly that is provided by...

Adding Controls to Excel and Word Documents

In the same way that you add ActiveX controls to a Word document or Excel worksheet and you program against the controls using VBA, you can add Windows Forms controls to your document (or worksheet) with VSTO. To add controls to the document, you drag them from the Toolbox to an area on your document. The controls can be placed anywhere on the document surface except within a header or footer. You can add controls to your document at design time or at run time. At design time, the document (or...

Creating a Test Document with Cached Data

Using VSTO, create an Excel workbook project called CachedDataSample. 2. In cell A1, type First Name, and in cell A2, type Last Name. 3. Select cell B1, and create a named range called FirstName. Select cell B2, and create a named range called LastName. The document should look like the one in Figure 13.2. Figure 13.2. Cached data sample project Figure 13.2. Cached data sample project 4. Right-click Sheetl.vb in Solution Explorer or Sheetl in the designer, and click View Code. Add the code in...

Recognizing Patterns of Text

Regular expressions can also be used to search for patterns of text. For example, if you want to search for a text pattern that starts with the letter s and ends with the letters rt (so that you would find words such as smart, start, skirt, and sport), you can use a regular expression. The .NET Framework has a number of regular expression classes that can be referenced in the System.Text.RegularExpressions namespace. You can add regular expressions to the list of smart tag expressions by...

Creating Toolbar Buttons

In Chapter 7 (Customizing Excel with VSTO), you learned how to convert a simple VBA macro to Visual Basic 2005 code. In this section we modify that code so that bold formatting toggles on and off in the Click event handler of a button that we add to the Standard toolbar. This code is similar to the code shown in Chapter 6 (Customizing Word with VSTO), but here it is specific to Excel. We further extend this code example to show you how to add a custom icon to the button. First, you'll write...

Available Windows Forms Controls

In Chapter 4, you looked at some of the differences between the ActiveX controls in VBA and the equivalent Windows Forms controls. Table 8.1 lists all the Windows Forms controls that appear on the Toolbox when a Windows Form has focus and when the document has focus (DesignTime Support in Document). The table includes a short description of each control, but this book does not go into detail about each control's properties and events. We encourage you to explore the VSTO documentation to learn...

Special Enhancements to the Bookmark

In addition to enabling data binding and providing events, VSTO adds some additional special enhancements to the Bookmark control. VSTO combines an Interop bookmark with an Interop range, and therefore you will find many more properties and methods on a VSTO bookmark than can be found on an Interop bookmark. If you take a look in the Object Browser, you can see the differences. The right pane of Figure 6.20 shows all the members of the Interop bookmark. Object Browser ThisDocument.vb* ( Start...

Selection Change Event Handler

The code in Listing 7.35 shows how you can write code in the Selection-Change event handler of the list object to display the address of the selected range in the status bar. Listing 7.35. Displaying the address of a range of cells selected in the list object Private Sub List1_SelectionChange(ByVal Target As _ Microsoft.Office.Interop.Excel.Range) _ Handles List1.SelectionChange Dim currentRange As Excel.Range Me.Application.Selection Application.StatusBar currentRange.Address

Application and Deployment Manifests

A VSTO solution consists of a document that is linked to an assembly. This enables you to easily update solutions distributed to your users in the enterprise. By contrast, VBA code is embedded in the document, so you distribute the document by making a copy of the code for each copy of the document. This makes it almost impossible to update the code if a bug or security vulnerability is discovered. Using VBA and Word, you could use a global template containing VBA code that is available to any...

In Solution Explorer rightclick Ribbonvb and then click View Code Ribbonvb opens in code view in Visual Studio Expand

Jij-j'jj i-j i _ - t , i y j jij-j'jj i-j i _ - t , i y j < V* Itarikn.l.il. THrfddftub Ffc 5r n* t X Implement Off ice.ISibboaEsttensibilitr PC Ivrit-r aUjun to Of f ice. TP LbbcmUI j Rttcrl.nW W 13 -.> *r(teftddrijet S Public function 3 lCuSte Ui (ByVal iIMjuqID A3 aviltiy) JLs ati in Implements CUtlfe. iftltitionEiilent Peturri CecfieaaurceTeKt (SanipleAdam. P ifafaonl.xiil,T) Cntl function 1 1*11 ion Pibbon Callbacks Public Sub 0nU**t(8vv< .) ttWK> nin to Offk r.uubbonOT) Public 3...

Creating an Interop Excel Application

To create the sample Excel application, which calculates the distance between two points in two-dimensional space, you will use a user defined function written in VBA. 1. Open a new Excel document, and save it as CalculateDistance.xls to a location of your choice. 2. Create the spreadsheet shown in Figure 12.8. JI > - I Z - Ii 100 B Get Work Items i Pubtsh Refresh Configure List D j M B Figure 12.8. Calculating the distance between two points Figure 12.8. Calculating the distance between two...

Overriding BuiltIn Commands

It is easy to override a built-in Word command using VBA. To do so, you create a subroutine that has the same name as the built-in command. Each time the user clicks the button for that command on the toolbar or menu or presses a keyboard shortcut, your custom subroutine runs instead of Word's built-in command. You can't do this in VSTO because of limitations in the Word and Excel architecture. One thing you can do is to create a callback from VBA into your managed code within VSTO. You can use...

Variable Declaration and Scope

When you declare a variable within a Visual Basic 2005 class, the variable is available only within that instance of the class and cannot be accessed by another instance. If you declare the variable as Shared, it is available to all instances of the class. In VBA, variables declared within a code block, such as a loop, are available locally to the entire procedure, but variables in Visual Basic 2005 are available only within the code block itself. If you declare a variable within a looping...

Taking Action on a Smart

The reason you add a smart tag to a particular term or phrase is to allow users to take further action based on the recognized term. For example, with Word's built-in smart tags, you can send an e-mail addressed to the recognized name, add the name to your contact list, schedule a meeting with the person, and so on. You can also create multiple actions for the smart tags that you create. You do this by passing an array of actions to the smart tag's Actions property. Because you must pass an...

Adding a User Control to Your Project

Right-click the project in Solution Explorer, point to Add, and click User Control. 2. In the Add New Item dialog box, select User Control, leave the default name of UserControl1.vb, and then click OK. This adds a class to your project called UserControll.vb. The class has a code view and a design view. By default, the user control appears in Visual Studio in design view. You can then add controls and set their properties in this view. 3. Resize the user control so that its Width is 210, and...

Replace the XML markup in Contact Ribbonxml with the markup in Listing

Changing the ContactRibbon XML file < ribbon> < tabs> < tab id ContactRibbon.Tab label ContactRibbon Tab> < group id ContactRibbon.Group label ContactRibbon Group> < toggleButton label ContactRibbon Toggle Button 1 screentip ToggleButton1 Screentip > < toggleButton label ContactRibbon Toggle Button 2 screentip ToggleButton2 Screentip onAction OnToggleButton > < group> < tab> < tabs> < ribbon> < customUI>

Hooking Up Form Region Controls

You need to hook up the form region controls so that you can handle the control events. Outlook 2007 calls BeforeFormRegionShow, passing a reference to the form region. This is where you will hook up the controls. 1. In the main menu click Project, and then click Add Reference. 2. In the COM tab of the Add References dialog box, select Microsoft Forms 2.0 Object Library. This action adds a reference to Microsoft.vbe.Interop.Forms. 3. Add the Imports Microsoft.vbe.Interop.Forms statement to the...

Reading and Writing the Document Data Cache

In the preceding section you created the test document that you will use to read and write the data using the ServerDocument API. In the following steps, you will create a new Console application that will read and write the cached data fields from the document. 1. Create a new Visual Basic Console application project. 2. Add a reference to the VSTO runtime, as shown in Figure 13.4. On the Project menu, click Add Reference. In the .NET tab of the Add References dialog box, select NET I COM...

Named Range Control Events

Table 7.1 shows the events that are available for a NamedRange control in VSTO. Table 7.1. Events of the NamedRange Control Table 7.1. Events of the NamedRange Control Raised when the NamedRange control is double-clicked. The BeforeDoubleClick event handler enables you to take action when a user double-clicks text within a named range, before the default action for double-clicking the mouse button occurs. Raised when the NamedRange control is right-clicked. The BeforeRightClick event handler...

XMLMapped Range Control Events

Table 7.3 shows the events that are available for an XMLMappedRange control in VSTO. Table 7.3. Events of the XMLMappedRange Control Table 7.3. Events of the XMLMappedRange Control Raised when the XMLMappedRange control is double-clicked. The BeforeDoubleClick event handler of an XMLMappedRange control enables you to take action when a user doubleclicks text within an XML mapped range, before the default action occurs. Raised when the XMLMappedRange control is right-clicked. The...

Using the Publish Wizard

Create an Excel Workbook project with VSTO. 2. Add the code in Listing 11.1 to the ThisWorkbook_Startup method. This action creates an empty actions pane with a blue background. The background color makes it easy for you to see that your code is running. Listing 11.1. Creating an empty actions pane with a blue background ActionsPane.BackColor Color.Blue ActionsPane.Visible True You control the publish version of the application from the Publish tab of the project Properties page....

Adding Host Controls at Run Time

Most host controls can be added to the document at run time. The exception to this rule is related to XML mapping. As you learned earlier, you can add XML-mapped elements only by using the XML Structure task pane. To programmatically add other host controls, such as a ListObject or NamedRange, you must use helper methods provided by VSTO. If you programmatically add a list object, chart, or range object in the same way you add it in VBA, it is created as an Interop object and not a VSTO object....

Windows Forms Controls in Excel

When you add controls to an Excel worksheet, they are added as floating controls. You can move a control to any area of your worksheet, including positioning it between columns or rows, as shown in Figure 8.19. These controls do not automatically resize when you resize a column or row. You can change this behavior by using the Format Control dialog box. J tf U J A W J - gt - C - S, gt - 5. m Figure 8.19. Placing controls on an Excel worksheet Figure 8.19. Placing controls on an Excel worksheet...

Listing illustrates how to handle its events Listing Adding a combo box control

Public Sub OnChange ByVal control As Office.IRibbonControl, _ ByVal text As String Dim CurrentRange As Excel.Range Globals.ThisAddin _ .Application.Selection CurrentRange.Font.Subscript True Case Superscript CurrentRange.Font.Superscript True CurrentRange.Font.Subscript False CurrentRange.Font.Superscript False End Select End Sub The Custom group for these controls is illustrated in Figure 14.24. Yl , J . Bookl- Microsoft Excel Home Insert Page Layout Formulas Data Review View Custom Tab Yl , J...

Ribbons in Outlook

The Outlook application supports the Ribbon in individual Inspectors, but not on the main Outlook window the Explorer . The Explorer has the traditional menu and toolbars that you are familiar with however, if you open an individual e-mail item, task, meeting request, or other Outlook item Inspector , the UI displays the Ribbon. In this section you'll create an Outlook add-in project that has two Ribbons. The first one will be used for the read mail Inspector, and the second one will be used...

Working with XML

Because XML is case sensitive, it is easy to make errors that might be difficult to find. You can turn on error messages for the Ribbon so that you are notified of the type of error that occurred, rather than the application simply not displaying the customization. Note You could have added a new Format tab in addition to the built-in Add-Ins tab, rather than replacing it. For example, in the XML code shown in Listing 14.2, if you change the case of idMso to idMSO and then run the code, you'll...

Accessing a Host Control from an Underlying Interop Object

Each host control has an associated underlying Interop object. You can access this object from the host control by using its InnerObject method. However, there is no way to do the opposite access a host control from the underlying Interop object. VSTO does not provide a collection for each of the host controls instead, there is a single Controls collection, which can contain host controls as well as Windows Forms controls. Although a VSTO Bookmarks collection does not exist, there is an Interop...

How VSTO Integrates with Visual Studio

When you create a Word or Excel solutions, using VSTO, you can interact with the Word or Excel application directly from within Visual Studio. This is because VSTO is integrated with Visual Studio. After you have created a new Excel or Word document or template project, the document is available within the Visual Studio environment as a designer. In fact, the entire application is available to you right inside Visual Studio A designer is a container for the user interface of the application you...

Creating Word and Excel Smart Tags with VSTO

Because VSTO smart tags are available only to the document or workbook in which you add them, you can scope the smart tags to a specific solution rather than create smart tags that might be available to any document that is opened. VSTO provides two smart tag classes Microsoft.Office.Tools.Excel.SmartTag and Microsoft.Office.Tools.Word.SmartTag that enable you to add smart tags to your document or workbook. You enable Word or Excel to recognize certain terms by using these classes to add...

Overriding Excel Commands

Using VBA, it is easy to override a built-in Excel command. All you need to do is to change the OnAction property of an existing button to point to a procedure that has your modification. Of course, you need to do this for the button as well as the menu item. Listing 7.9 shows how you might override the Save button in Excel using VBA. Listing 7.9. Overriding the Save button in Excel with VBA Sub OverrideButton Dim myNewCommand As Office.CommandBarButton Set myNewCommand myNewCommand.OnAction...

Hooking Up the Form Region

You now need to hook up the add-in to the form region. Outlook uses a service-based model. Outlook calls the RequestService method of the ThisAddin class, passing the GUID of the service it is looking for in this case, a class that implements FormRegionStartup. You also need to declare a local variable to hold a reference to the FormRegionStartup class that you pass to the service request. Add the code in Listing 14.41 to the ThisAddin class. Listing 14.41. Hooking up a form region public class...

List Object Control Events

Table 7.2 shows the events that are available for a ListObject control in VSTO. Table 7.2. Events of the ListObject Control Table 7.2. Events of the ListObject Control Raised when a user attempts to add a new row to a data-bound ListObject. This event is not raised when a new row is programmatically added to the ListObject, only when the user interface is used to add the row. Raised when the ListObject control is double-clicked. The BeforeDoubleClick event handler of a ListObject control...

Generic Classes

Generic classes are a new feature in the .NET Framework and are supported in Visual Basic 2005. A generic class is a single class that provides functionality for different data types, without the need to write a separate class definition for each data type. You can also define generic methods, structures, and interfaces. A generic class uses type parameters as placeholders for the data types. The code example in Listing 3.10 shows the declaration of a generic class using t to represent the type...

Customizing Menus and Toolbars in Outlook

One of the main points of entry to code in Microsoft Office 2003 applications is through their menus and toolbars. Using the code you created in the preceding section to add a task, you can add additional code to call this code from a menu item that you create. In this example, you will delete the toolbar if it already exists and then re-create it. We take this approach instead of setting a reference to the existing toolbar if found because we don't know what state the toolbar was in when...

Control Type

When you add a Windows Forms control to a document, VSTO creates its version of the Windows Forms control. Instead of the control being in the System.Windows.Forms namespace, it is in the Microsoft.Office.Tools.Word.Controls namespace or the Microsoft.Office.Tools.Excel.Controls namespace, depending on which application you're using. The document or worksheet does not know anything about Windows Forms controls or their behaviors. ActiveX controls are the only thing that documents are aware of....

Creating and Registering the Form Region Manifest

You need to create a form region manifest file and register it in the registry. Let's look at how to do this. 1. To add a form region manifest to your project, click Project, and then in the main menu click Add New Item. 2. In the Templates pane of the Add New Item dialog box, select XML File. 3. Name the new item MySimpleFormRegionManifest.xml, and add the XML in Listing 14.33 to the MySimpleFormRegionManifest.xml file you just added. 4. On the Project menu, click SimpleFormRegion Properties....

Adding Controls to the Task Pane

Adding controls to the task pane is very similar to adding controls to a Windows Form. Using VSTO, you add controls to the ActionsPane object for Word 2003 and Excel 2003 solutions. If you're using VSTO 2005 SE and Office 2007, you can add the controls to the Custom task pane, which is available to any document you have opened. The remainder of this section describes controls on the actions pane, but it is also applicable to the Custom task pane. In Chapter 14 you'll learn more about adding...

Converting an Outlook Macro to a VSTO Addin

In this section you will create a simple VBA macro for Outlook and convert the code to a VSTO add-in. The VBA code is in the ItemSend event handler of the Application object in a VBA project, as shown in Listing 10.1. Listing 10.1. VBA macro that checks for a subject on an outgoing e-mail Private Sub Application_ItemSend ByVal Item As Object, _ Cancel As Boolean If Item.Class olMail Then If Item.Subject Then sendMessage MsgBox Subject text is missing. amp _ vbCrLf amp vbCrLf amp Do you want to...

Document Events

Following are the events that are available for a Document object in VSTO. Some of these events are available on the document in VBA and are exposed in the primary interop assembly PIA , others were added from the Application object, and still others are specific to VSTO. Notice that some of the event names have been changed. For example, the Close event is renamed CloseEvent, because there is both a Close method and a Close event on the Document object. To avoid collisions, VSTO has changed...

The Breakpoints Window

The Breakpoints window lets you see all the breakpoints in your application in one place. You can easily disable and enable breakpoints using the check boxes next to each breakpoint in the window. To view the Breakpoints window, click the Debug menu, point to Windows, and click Breakpoints. Figure 2.35 shows the Breakpoints window, with the current breakpoint displayed in bold. 1 0 1 Sheet l.vbj line 28 character 9 no condition -0 1 Sheet l.vbj line 31 character 9 no condition -0 1 Sheet2.vbj...

Accessing an Interop Object from a Host Control

Sometimes you need to access the Interop object associated with a given host control. For example, you might be working with the host controls and want to call a method that specifically requires an Interop object. You cannot cast a VSTO object into an Interop object, but you can instead call the InnerObject property of the host control to return its underlying Interop object. For example, if you wanted to write a solution that enables users to add a NamedRange control to the worksheet by...

Project Properties

You can set various properties for your project using the Project Designer. To open the Project Designer, select lt ProjectName gt Properties from the Project menu. Or you can double-click the MyProject node in Solution Explorer, as shown in Figure 2.l9. Several pages are available in the Project Designer. You can navigate to each page by clicking the appropriate tab on the left side of the window. Table 2.2 briefly describes each page. Table 2.2. Project Files Output During Build Table 2.2....

Vba Permissionset

In the Permission Set tab, you define the permissions that the code group grants as shown in Figure 11.5. VSTO solutions must be given full trust in order to run. The default behavior is for the VSTO project system to grant trust to your project, but you can turn off this behavior using your project's Trust Assemblies Location property, as shown in Figure 11.6. Figure 11.5. Permission Set tab of the code group Properties page Figure 11.5. Permission Set tab of the code group Properties page Add...

And Also Operator

The AndAlso operator is used to evaluate two expressions but evaluates the second expression only if the first expression is True. For example, if you want to access a property of a Bookmark object only if the bookmark exists thus avoiding an error , you can use the AndAlso statement, as shown in Listing 4.7. This technique is often referred to as short circuiting. Listing 4.7. Using the AndAlso operator If Bookmark1 IsNot Nothing AndAlso Bookmark1.Bold Then MsgBox The bookmark text is bold End...

Creating Custom Task Panes

Creating a Custom task pane in Office 2007 is as easy as creating a document-level actions pane for Word 2003 or Excel 2003. With VSTO 2005 SE, you first create an add-in project for an application that supports the Custom task pane, and then you add a user control to the application's CustomTaskPanes collection. VSTO 2005 SE supports Custom task panes for Word 2007, Excel 2007, Outlook 2007, InfoPath 2007, and PowerPoint 2007. Let's take a closer look at creating a simple Custom task pane for...

Granting Access to the VBA Project System

The very first time you create a VSTO project for Word and Excel, VSTO displays a dialog box informing you that the project must have access to the Visual Basic for Applications project system, as shown in Figure 2.5. You must click OK to create a VSTO project. If you click Cancel, the project will not be created. Vou must explicitly enable access to the Microsoft Office Visual Basic for Applications project system before you can create or open a Visual Studio Tools for the Microsoft Office...

Selected IndexChanged Event Handler

You can write code in the SelectedIndexChanged event handler to show the value of the currently selected range in a text box on the actions pane, as shown in Listing 7.34. Listing 7.34. Displaying the current value of the list object in the actions pane Dim myTextbox As New TextBox Private Sub List1_SelectedIndexChanged ByVal sender As _ Object, ByVal e As System.EventArgs Handles _ List1.SelectedIndexChanged Dim currentRange As Excel.Range Me.Application.Selection myTextbox.Text...

Reenabling a Soft Disabled Addin

Create an Outlook add-in project with VSTO. 2. In the Startup event handler of ThisApplication, add the code in Listing 10.14. Listing 10.14. Creating an error at startup Private Sub ThisApplication_Startup ByVal sender As Object, _ ByVal e As System.EventArgs Handles Me.Startup Dim first As Integer 12 Dim second As Integer 0 Dim DivideByZero As Integer first second MsgBox DivideByZero 3. Press F5 to run the code. The message box does not display the code throws a divide-by-zero exception,...

Managing the Actions Pane

Several layers of containers make up the actions pane. Figure 5.2 illustrates these layers. Figure 5.2. Containers within the actions pane Figure 5.2. Containers within the actions pane The first container is the Office task pane itself. This container holds individual panes, such as the Document Actions task pane. The ActionsPane object is contained by the Document Actions task pane and acts as a container for Windows Forms controls. You can program-matically add Windows Forms controls...

Microsoft Pss Vsto Client Troubleshooter

It can be difficult to verify that you have configured the client machine correctly with all the requirements. Some of this difficulty can be attributed to the different ways Office can be installed. You cannot always assume that Office has been installed to allow .NET programmability. However, you can use a tool created by the VSTO product support team that will analyze a client machine to determine whether the correct software is installed to run a deployed VSTO solution. This Microsoft PSS...

What Is a Task Pane

The mark of good action is that it appears inevitable in retrospect. Robert Louis Stevenson To gather user input, Office developers typically display forms to be filled out by end users. There are disadvantages to this approach because it often forces users to attend to the form before they can continue working in the document. The form also obstructs users' view of the contents of the document. In this chapter, you will learn how to customize the Document Actions task pane to provide a rich...

Caption Property

The Caption property is a read-only property that enables you to retrieve the text that is displayed at the top of the smart tag menu. The Caption property is set when you create the smart tag, and it passes the smart tag's unique namespace identifier and caption. In the example in Listing 9.4, the caption passed is Control Smart Tag. It is displayed at the top of the Smart Tag menu, followed by the recognized term or expression, as shown in Figure 9.7. Figure 9.7. The caption of a smart tag

Customizing the BuiltIn Ribbon

Rather than create your own tab, you might instead want to customize an existing built-in tab. Remember that just because you can do something, it doesn't mean that you should There are some things to keep in mind as you customize the Ribbon. Although you can hide tabs and groups, you should avoid doing so. Other installed add-ins might rely on these built-in items that you've hidden. You cannot add buttons to a built-in group. This is unfortunate because in some situations it would make sense...