[VBA Beginner] How to Add Notes (Comments) to Cells | Using AddComment and Precautions

目次

Introduction

Excel includes a feature to add “Notes (Legacy Comments)” to cells. By using VBA, the process of automatically inserting these notes can be easily implemented.

This article provides a detailed explanation of the basic usage of the AddComment method and the logic for determining whether a note already exists, accompanied by specific sample code.


VBA Code: Adding a Note to a Cell

The following code checks if cell C3 already contains a note and adds one only if it is empty.

Sub AddNoteIfNoneExists()
    Dim targetCell As Range
    
    ' Set the target cell to C3
    Set targetCell = Range("C3")

    ' Determine if a note already exists
    If targetCell.Comment Is Nothing Then
        ' Add a note if none exists
        targetCell.AddComment "A note has been added to this cell."
    Else
        ' Display a message if a comment is already present
        MsgBox "A comment already exists."
    End If
End Sub

Key Points of the Process

  • targetCell: A variable pointing to the target cell (e.g., Range("C3")).
  • Comment Is Nothing: This property is used to check for the presence of a note. If no note exists, it returns Nothing.
  • AddComment: This method inserts a note. It is important to note that attempting to use AddComment on a cell that already has one will result in a runtime error.
  • Preventing Overwrites: By using an If statement to check for existing comments, the macro avoids errors and can notify the user instead of overwriting.

Precautions: Differences by Excel Version

It is important to distinguish between the types of comments available in different versions of Excel.

Excel VersionFeature Details
Excel 2019 and earlierThe comment feature is referred to as “Notes” and is fully compatible with the AddComment method.
Excel 365 / Excel 2019+Modern Threaded Comments (used for conversations) are handled via the CommentThreaded object.

The AddComment method specifically targets the traditional “Notes” (yellow boxes). For modern threaded conversations, different VBA objects must be utilized.


Summary

  • Use the AddComment method to automate note insertion.
  • Always verify the Comment property first to prevent runtime errors.
  • Recognize that AddComment applies to legacy “Notes,” not modern “Threaded Comments.”

Mastering these basics allows for the creation of automated spreadsheets that can provide contextual information or audit logs to other users.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次