一、獲取單元格的備注
Private SubCommandButton1_Click()
Dim strGotIt As String
strGotIt
= WorksheetFunction.Clean(Range("A1").Comment.Text)
MsgBox strGotIt
End Sub
Range.Comment.Text用於得到單元格的備注文本,如果當前單元格沒有添加備注,則會引發異常。注意代碼中使用了WorksheetFunction對象,該對象是Excel的系統對象,它提供了很多系統函數,這裡用到的Clean函數用於清楚指定文本中的所有關鍵字(特殊字符),具體信息可以查閱Excel自帶的幫助文檔,裡面提供的函數非常多。下面是一個使用Application.WorksheetFunction.Substitute函數的例子,其中第一個Substitute將給定的字符串中的author:替換為空字符串,第二個Substitute將給定的字符串中的空格替換為空字符串。
Private FunctionCleanComment(author As String, cmt As String) As String
Dim tmp As String
tmp = Application.WorksheetFunction.Substitute(cmt, author & ":", "")
tmp = Application.WorksheetFunction.Substitute(tmp, Chr(10), "")
CleanComment = tmp
End Function
二、修改Excel單元格內容時自動給單元格添加Comments信息
Private SubWorksheet_Change(ByVal Target As Excel.Range)
Dim newText As String
Dim oldText As String
For Each cell In Target
With cell
On Error Resume Next
oldText = .Comment.Text
If Err <> 0 Then .AddComment
newText = oldText & " Changed by " & Application.UserName & " at " & Now & vbLf
MsgBoxnewText
.Comment.Text newText
.Comment.Visible = True
.Comment.Shape.Select
Selection.AutoSize = True
.Comment.Visible = False
End With
Next cell
End Sub
Comments內容可以根據需要自己修改,Worksheet_Change方法在Worksheet單元格內容被修改時執行。
三、改變Comment標簽的顯示狀態
SubToggleComments()
If Application.DisplayCommentIndicator = xlCommentAndIndicator Then
Application.DisplayCommentIndicator = xlCommentIndicatorOnly
Else
Application.DisplayCommentIndicator = xlCommentAndIndicator
End If
End Sub
Application.DisplayCommentIndicator有三種狀態:xlCommentAndIndicator-始終顯示Comment標簽、xlCommentIndicatorOnly-當鼠標指向單元格的Comment pointer時顯示Comment標簽、xlNoIndicator-隱藏Comment標簽和單元格的Comment pointer。
四、改變Comment標簽的默認大小
SubCommentFitter1()
With Range("A1").Comment
.Shape.Width = 150
.Shape.Height = 300
End With
End Sub
注意:舊版本中的Range.NoteText方法同樣可以返回單元格中的Comment,按照Excel的幫助文檔中的介紹,建議在新版本中統一使用Range.Comment方法。