Dela via


How to: Create Smart Tags With Custom Recognizers in Excel

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Document-level projects

  • Excel 2003

  • Excel 2007

  • Word 2003

  • Word 2007

Application-level projects

  • Excel 2007

  • Word 2007

For more information, see Features Available by Application and Project Type.

You can control how Microsoft Office Excel recognizes smart tags in workbooks by deriving from the Microsoft.Office.Tools.Excel.SmartTag class and overriding the Recognize method.

To run a smart tag, end users must have smart tags enabled in Word or Excel. For more information, see How to: Enable Smart Tags in Word and Excel.

To add a smart tag with a custom recognizer to an Excel workbook

  1. Create a new document-level or application-level project for Excel. For more information, see How to: Create Visual Studio Tools for Office Projects.

    Note

    To use an application-level project, you must have Visual Studio 2008 Service Pack 1 (SP1) installed.

  2. Add a reference to Microsoft Smart Tags 2.0 Type Library from the COM tab of the Add Reference dialog box.

  3. Add a class file to the project and create a class that inherits from Microsoft.Office.Tools.Excel.SmartTag.

  4. In the new class, create the actions for the smart tags. Actions are items that appear on the smart tags menu. Create actions by adding instances of the Action type to your class's Actions collection.

  5. Override the Recognize method to implement your own custom recognizing behavior. Your implementation of Recognize must call the PersistTag method to make Excel recognize the smart tag.

  6. Create event handlers to respond to the Click event, and optionally the BeforeCaptionShow event, of the actions that you created.

  7. In the code file for the project workbook, add the smart tag instance to the VstoSmartTags property of the ThisWorkbook class (for a document-level project), or the VstoSmartTags property of the ThisAddIn class (for an application-level project).

    Note

    If you are using an application-level project that you created before you installed SP1, you must modify the project to generate the VstoSmartTags property. For more information, see How to: Add Application-Level Smart Tags to Projects That Were Created Before SP1.

Example

The following code example shows how to create a custom smart tag in an Excel workbook. The example overrides the Recognize method to recognize the terms sales and organization in a worksheet cell. The Recognize method adds a key and value pair to the collection of keyed properties for the smart tag. The method then calls the PersistTag method to recognize the smart tag and save the new smart tag property. To test the example, type the words sales and organization in different cells in the workbook, and then try the smart tag actions. One action displays the corresponding property value for the recognized term, and the other action displays the smart tag namespace and caption.

Imports Microsoft.Office.Tools.Excel
Imports Microsoft.Office.Interop.SmartTag

Public Class CustomSmartTag
    Inherits SmartTag

    ' Declare Actions for this SmartTag 
    WithEvents Action1 As New Action("Display property value")
    WithEvents Action2 As New Action("Display smart tag details")

    Public Sub New()
        MyBase.New("https://www.contoso.com/Demo#DemoSmartTag", _
            "Custom Smart Tag")
        Me.Terms.AddRange(New String() {"sales", "organization"})
        Actions = New Action() {Action1, Action2}
    End Sub 

    Protected Overrides Sub Recognize(ByVal text As String, _
        ByVal site As ISmartTagRecognizerSite, _
        ByVal tokenList As ISmartTagTokenList)

        ' Determine whether each smart tag term exists in  
        ' the document text. 
        Dim Term As String 
        For Each Term In Me.Terms

            ' Search the cell text for the first instance of  
            ' the current smart tag term. 
            Dim index As Integer = Me.CellText.IndexOf(Term, 0)

            If (index >= 0) Then 

                ' Create a smart tag token and a property bag for the  
                ' recognized term. 
                Dim propertyBag As ISmartTagProperties = _
                    site.GetNewPropertyBag()

                ' Write a new property value. 
                Dim key As String = "Key1"
                propertyBag.Write(key, DateTime.Now)

                ' Attach the smart tag to the term in the document 
                Me.PersistTag(propertyBag)

                ' This implementation only finds the first instance 
                ' of a smart tag term in the cell.  
                Exit For 
            End If 
        Next 
    End Sub 

    ' This action displays the property value for the term. 
    Private Sub Action1_Click(ByVal sender As Object, _
        ByVal e As ActionEventArgs) Handles Action1.Click

        Dim propertyBag As ISmartTagProperties = e.Properties
        Dim key As String = "Key1"
        MsgBox("The corresponding value of " & _
            key & " is: " & propertyBag.Read(key))
    End Sub 

    ' This action displays smart tag details. 
    Private Sub Action2_Click(ByVal sender As Object, _
        ByVal e As ActionEventArgs) Handles Action2.Click

        MsgBox("The current smart tag caption is '" & _
            Me.Caption & "'. The current smart tag type is '" & _
            Me.SmartTagType & "'.")
    End Sub 
End Class
using System;
using System.Windows.Forms;
using Microsoft.Office.Tools.Excel;
using Microsoft.Office.Interop.SmartTag;

namespace Trin_ExcelDerivedSmartTags
{
    public class CustomSmartTag : SmartTag {

        // Declare Actions for this SmartTag
        Microsoft.Office.Tools.Excel.Action Action1 =
            new Microsoft.Office.Tools.Excel.Action("Display property value");
        Microsoft.Office.Tools.Excel.Action Action2 =
            new Microsoft.Office.Tools.Excel.Action("Display smart tag details");

        public CustomSmartTag() : base(
            "https://www.contoso.com/Demo#DemoSmartTag", 
            "Custom Smart Tag")
        {
            this.Terms.AddRange(new string[] { 
                "sales", "organization" });
            Actions = new Microsoft.Office.Tools.Excel.Action[] { Action1, Action2 };
            Action1.Click +=
                new ActionClickEventHandler(Action1_Click);
            Action2.Click += 
                new ActionClickEventHandler(Action2_Click);
        }

        protected override void Recognize(string text, 
            ISmartTagRecognizerSite site, ISmartTagTokenList tokenList)
        {
            // Determine whether each smart tag term exists in  
            // the document text. 
            foreach (string term in this.Terms)
            {
                // Search the cell text for the first instance of  
                // the current smart tag term. 
                int index = this.CellText.IndexOf(term, 0);

                if (index >= 0)
                {
                    // Create a smart tag token and a property bag for the  
                    // recognized term.
                    ISmartTagProperties propertyBag = 
                        site.GetNewPropertyBag();

                    // Write a new property value.                  
                    string key = "Key1";
                    propertyBag.Write(key, DateTime.Now.ToString());

                    // Attach the smart tag to the term in the document 
                    this.PersistTag(propertyBag);

                    // This implementation only finds the first instance 
                    // of a smart tag term in the cell.  
                    break;
                }
            }
        }

        // This action displays the property value for the term. 
        private void Action1_Click(object sender, ActionEventArgs e)
        {
            ISmartTagProperties propertyBag = e.Properties;
            string key = "Key1";
            MessageBox.Show("The corresponding value of " + key +
                " is: " + propertyBag.get_Read(key));
        }

        // This action displays smart tag details. 
        private void Action2_Click(object sender, ActionEventArgs e)
        {
            MessageBox.Show("The current smart tag caption is '" + 
                this.Caption + "'. The current smart tag type is '" + 
                this.SmartTagType + "'.");
        }
    }
}

Compiling the Code

  • Add a reference in the project to Microsoft Smart Tags 2.0 Type Library from the COM tab of the Add Reference dialog box. Ensure that the Copy Local property of the reference is false. If it is true, the reference is not to the correct primary interop assembly and you must install the assembly from the Microsoft Office installation media. For more information, see How to: Install Office Primary Interop Assemblies.

  • Place the example code in a new class file named CustomSmartTag.

  • In C#, change the namespace to match the project name.

  • Add Imports (in Visual Basic) or using (in C#) statements for the Microsoft.Office.Tools.Excel and Microsoft.Office.Interop.SmartTag namespaces at the top of the class file.

  • Add the following code to the ThisWorkbook_Startup or ThisAddIn_Startup event handler in your project. This code adds the custom smart tag to the workbook.

    Me.VstoSmartTags.Add(New CustomSmartTag())
    
    this.VstoSmartTags.Add(new CustomSmartTag());
    

Security

You must enable smart tags in Excel. By default, they are not enabled. For more information, see How to: Enable Smart Tags in Word and Excel.

See Also

Tasks

How to: Enable Smart Tags in Word and Excel

How to: Add Smart Tags to Word Documents

How to: Add Smart Tags to Excel Workbooks

How to: Create Smart Tags With Custom Recognizers in Word

Walkthrough: Creating a Smart Tag by Using a Document-Level Customization

Walkthrough: Creating a Smart Tag by Using an Application-Level Add-In

Concepts

Smart Tags Overview

Smart Tags Architecture

Office UI Customization

Change History

Date

History

Reason

July 2008

Added new information for application-level add-ins.

SP1 feature change.