Export (0) Print
Expand All
Expand Minimize

How to: Refer to Worksheet Ranges in Code

NoteNote

Some code examples in this topic use the this or Me keyword or the Globals class in a way that is specific to document-level customizations, or they rely on features of document-level customizations such as host controls. These examples can be compiled only if you have the required applications installed. For more information, see Features Available by Product Combination.

The Microsoft.Office.Interop.Excel.Range class is quite flexible. Sometimes a range is a single object, and other times it represents a collection of objects. It has Item and Count members, even though a range often refers to a single object, making it sometimes confusing to figure out exactly how to use a Microsoft.Office.Interop.Excel.Range object.

The range can be one of two types:

Using Host Controls

To refer to a NamedRange control

  • Assign a string to the Value2 property of the Microsoft.Office.Tools.Excel.NamedRange control.

    Microsoft.Office.Tools.Excel.NamedRange NamedRange1 =
        this.Controls.AddNamedRange(this.get_Range("A1", missing), "NamedRange1");
    
    NamedRange1.Value2 = "Range value";
    
    

Using Excel Objects

To refer to a named Range object

  • Assign the named range to a variable and set the Value2 property to Range value.

    Excel.Range rng = this.Application.get_Range("A1", missing);
    
    rng.Value2 = "Range value";
    
    

Compiling the Code

  • This code must be placed in a sheet class, not in the ThisWorkbook class.

See Also

Community Additions

ADD
Show:
© 2014 Microsoft