How to: Send Values to Worksheet Cells

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 can put a value in a cell by using a range. The following examples use the Value2 property of the range instead of the Value property to avoid having to pass in parameters.

To send a value to a cell in a document-level customization

  • Create a NamedRange control on cell A1 of Sheet1, and assign a string value to the Value2 property. Place the following code in the Sheet1 class.

    Dim nr As Microsoft.Office.Tools.Excel.NamedRange = _
        Me.Controls.AddNamedRange(Me.Range("A1"), "NamedRange1")
    
    nr.Value2 = "Hello World"
    
    Microsoft.Office.Tools.Excel.NamedRange nr =
        this.Controls.AddNamedRange(this.Range["A1", missing], "NamedRange1");
    
    nr.Value2 = "Hello World";
    

To send a value to a cell in an application-level add-in

  • Create a Range that represents cell A1 of Sheet1, and assign a string value to the Value2 property.

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

Robust Programming

The following condition causes an exception:

  • The worksheet exists and is read-only (COMException class).

Security

User input can include information that is potentially malformed, malicious, or not valid. Always check that the values that a user enters conform to the requirements for your application before using the values. For more information, see User Input Validation in Windows Forms.

See Also

Tasks

How to: Refer to Worksheet Ranges in Code

How to: Add New Worksheets to Workbooks

Concepts

Working with Cells

NamedRange Control

Host Items and Host Controls Overview

The Variable missing and Optional Parameters in Office Solutions

Change History

Date

History

Reason

July 2008

Added a code example that can be used in an application-level add-in.

Customer feedback.