Share via


How to: Programmatically add and delete worksheet comments

Applies to: yesVisual Studio noVisual 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 can programmatically add and delete comments in Microsoft Office Excel worksheets. Comments can be added only to single cells, not to multi-cell ranges.

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.

Add and delete a comment in a document-level project

The following examples assume that there is a single-cell NamedRange control named dateComment on a worksheet named Sheet1.

To add a new comment to a named range

  1. Call the AddComment method of the NamedRange control and supply the comment text. This code must be placed in the Sheet1 class.

    this.dateComment.AddComment("Comment added " + DateTime.Now.ToString());
    
    Me.dateComment.AddComment("Comment added " & DateTime.Now)
    

To delete a comment from a named range

  1. Verify that a comment exists on the range and delete it. This code must be placed in the Sheet1 class.

    if (this.dateComment.Comment != null)
    {
        this.dateComment.Comment.Delete();
    }
    
    If Not Me.dateComment.Comment Is Nothing Then
        Me.dateComment.Comment.Delete()
    End If
    

Add and delete a comment in a VSTO Add-in project

The following examples assume that there is a single-cell Range named dateComment on the active worksheet.

To add a new comment to an Excel range

  1. Call the AddComment method of the Range and supply the comment text.

    Excel.Range dateComment = this.Application.get_Range("A1");
    dateComment.AddComment("Comment added " + DateTime.Now.ToString());
    
    Dim dateComment As Excel.Range = Me.Application.Range("A1")
    dateComment.AddComment("Comment added " & DateTime.Now)
    

To delete a comment from an Excel range

  1. Verify that a comment exists on the range and delete it.

    Excel.Range dateComment = this.Application.get_Range("A1");
    if (dateComment.Comment != null)
    {
        dateComment.Comment.Delete();
    }
    
    Dim dateComment As Excel.Range = Me.Application.Range("A1")
    If Not dateComment.Comment Is Nothing Then
        dateComment.Comment.Delete()
    End If
    

See also