存取儲存格註解有
NoteText 方法及使用
Comment 物件兩種方式。NoteText是來自舊版本的方法,現已由 Comment 物件所取代。NoteText方法適用簡易的存取,如果想對註解做更多樣化的控制,請使用 Comment 物件。
判斷目前儲存格是否有註解如果對一個不含註解的儲存格進行註解的相關操作,會發生錯誤。
可先利用以下方式判斷有無註解 --
Sub detect_Comment()
If ActiveCell.Comment Is Nothing Then
'沒有註解 Else
'含有註解 End If
'反過來說就是 If Not ActiveCell.Comment Is Nothing Then
'含有註解 End If
End Sub
PS. 以下的代碼看似可以判斷儲存格沒有註解 --
IF ActiveCell.NoteText = "" Then ...其實這個判斷式在 "註解為空白" 和 "沒有註解" 兩種情形下都會成立,並不能精確的判斷。因此還是建議利用 Comment 物件較理想,如上面的例子。
為儲存格加上註解 / 移除註解ActiveCell.AddComment
ActiveCell.Comment.Text "xxx"
或
ActiveCell.AddComment.Text "xxx"
移除註解
ActiveCell.Comment.Delete
NoteText說:天生我材必有用。
NoteText還是有它的好處,以下範例是判斷所有公式儲存格有無註解,無則加上,有則刪除。而 NoteText 簡化了加上/移除註解的代碼。
Sub SwitchComments( )
For Each c In Cells.SpecialCells(xlCellTypeformulas)
If c.Comment Is Nothing Then
c.NoteText c.Formula
Else
c.NoteText ""
End If
'可以再簡化成一行代碼 c.NoteText IIf(c.Comment Is Nothing, c.Formula, "")
Next
End Sub
註解應用範例:貼上註解 (並設定註解格式)Sub Macro1()
Dim cmt As Comment, data As New DataObject
Set cmt = ActiveCell.Comment
data.GetFromClipboard
'取得剪貼簿內容 If cmt Is Nothing Then
ActiveCell.AddComment
Set cmt = ActiveCell.Comment
cmt.Text data.GetText(1)
'設定註解內容 With cmt.Shape.TextFrame
'設定註解格式 .Characters.Font.FontStyle = "標準"
.AutoSize = True
End With
Else
'若註解已存在則添加於原註解之後 cmt.Text cmt.Text & vbLf & data.GetText(1)
End If
End Sub
PS. 本例因用到 DataObject,需引用 Microsoft Form 2.0 Object 項目。
請參考相關主題 -
Clipboard: 存取剪貼簿