How to: Programmatically refer to worksheet ranges in code
Applies to: Visual Studio Visual Studio for Mac
Note
This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here
You use a similar process to refer to the contents of a NamedRange control or a native Excel range object.
Applies to: The information in this topic applies to document-level projects and VSTO Add-in projects for Excel. For more information, see Features available by Office application and project type.
Use 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 NamedRange control. This code must be placed in a sheet class, not in the
ThisWorkbook
class.Microsoft.Office.Tools.Excel.NamedRange NamedRange1 = this.Controls.AddNamedRange(this.get_Range("A1"), "NamedRange1"); NamedRange1.Value2 = "Range value";
Dim NamedRange1 As Microsoft.Office.Tools.Excel.NamedRange = _ Me.Controls.AddNamedRange(Me.Range("A1"), "NamedRange1") NamedRange1.Value2 = "Range value"
Use 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.
Excel.Range rng = this.Application.get_Range("A1"); rng.Value2 = "Range value";
Dim rng As Excel.Range = Me.Application.Range("A1") rng.Value2 = "Range value"
See also
- Work with ranges
- How to: Programmatically check spelling in worksheets
- How to: Programmatically apply styles to ranges in workbooks
- How to: Programmatically automatically fill ranges with incrementally changing data
- How to: Programmatically search for text in worksheet ranges
- NamedRange control
- Host items and host controls overview
- Programmatic limitations of host items and host controls
- Optional parameters in Office solutions