Share via


How to: Refer to Worksheet Ranges in Code

Applies to

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

Project type

  • Document-level projects

  • Application-level projects

Microsoft Office version

  • Excel 2003

  • Excel 2007

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

You use a similar process to refer to the contents of a NamedRange control or a native Excel range object.

Using a NamedRange Control

The following example adds a NamedRange to a worksheet and then adds text to the cell in the range.

To refer to a NamedRange control

  • Assign a string to the Value2 property of the Microsoft.Office.Tools.Excel.NamedRange control. This code must be placed in a sheet class, not in the ThisWorkbook class.

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

Using Native Excel Ranges

The following example adds a native Excel range to a worksheet and then adds text to the cell in the range.

To refer to a native range object

  • Assign a string to the Value2 property of the range.

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

See Also

Tasks

How to: Check Spelling in Worksheets

How to: Apply Styles to Ranges in Workbooks

How to: Automatically Fill Ranges with Incrementally Changing Data

How to: Search for Text in Worksheet Ranges

Concepts

Working with Ranges

NamedRange Control

Host Items and Host Controls Overview

Programmatic Limitations of Host Items and Host Controls

The Variable missing and Optional Parameters in Office Solutions