Udostępnij za pośrednictwem


Global Access to Objects in Visual Studio Tools for Office Projects

You can use the Globals class to access several different project items from any code in the project.

How to Use Globals

Globals is a static class that keeps references to items in your project. By using the Globals class, you can reference the following items from any code in the project:

  • The Workbook or any Worksheet host item in an Excel workbook or template project. You access these host items by using properties of the Globals class that refer to each host item in your project. By default, the host item names are ThisWorkbook, Sheet1, Sheet2, and Sheet3.

  • The Document host item in a Word document or template project. The default name for this host item property is Globals.ThisDocument.

  • The AddIn host item in an application-level project. The default name for this host item property is Globals.ThisAddIn.

  • All Ribbons in your project that you customized by using the Ribbon Designer. You can access the Ribbons by using the Globals.Ribbons property.

  • All Outlook form regions in an Outlook add-in project. You can access the form regions by using the Globals.FormRegions property.

For example, you can write code to insert text into a NamedRange control on Sheet1 when a user clicks a button on the actions pane, as the following example illustrates.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles Button1.Click

    If Globals.Sheet1 IsNot Nothing Then
        Globals.Sheet1.NamedRange1.Value2 = Me.TextBox1.Text
    End If 

End Sub
private void button1_Click(object sender, EventArgs e)
        {
        if (Globals.Sheet1 != null)
            {
                Globals.Sheet1.namedRange1.Value2 = this.textBox1.Text;
            }
        }

Initializing the Globals Class

Code that attempts to use the Globals class before the document or add-in is completely initialized might throw a run time exception. For example, using Globals when declaring a class-level variable might fail because the Globals class might not be initialized with references to all of the host items before the declared object is instantiated.

Note

The Globals class is never initialized at design time, but control instances are created by the designer. This means that if you create a user control that calls methods of the Globals class, you must write code that checks whether the method returns null before you try to access it.

See Also

Concepts

Accessing the Ribbon at Run Time

Accessing a Form Region at Run Time

Host Items and Host Controls Overview

AddIn Host Item

Document Host Item

Workbook Host Item

Worksheet Host Item

Writing Code in Office Solutions