This documentation is archived and is not being maintained.

Global Access to Objects in the Project

You can use the Globals class to access the host items in a document-level project or application-level project from anywhere within the project.

For more information about host items, see Host Items and Host Controls Overview.

How to Use Globals

Globals is a static class that keeps references to all of the host items in your project. Using the Globals class, you can reference the following host items from any object in the project:

  • Workbook or any Worksheet in an Excel workbook project. You access these host items by using the ThisWorkbook, Sheet1, Sheet2, or Sheet3 properties of the Globals class.

  • Document in a Word document project. You access this host item by using the ThisDocument property of the Globals class.

  • AddIn in an application-level project created by using Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office System (VSTO 2005 SE). You access this host item by using the ThisAddIn property of the Globals class.

  • Microsoft.Office.Tools.Outlook.Application in an Outlook 2003 add-in created by using Microsoft Visual Studio 2005 Tools for the Microsoft Office System (VSTO 2005). You access this host item by using the ThisApplication property of the Globals class.

For example, you could 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 void button1_Click(object sender, EventArgs e)
{
if (Globals.Sheet1 != null)
    {
        Globals.Sheet1.namedRange1.Value2 = this.textBox1.Text;
    }
}

NoteNote

Code that attempts to use the Globals class before the document 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.

NoteNote

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

Show: