萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Excel 教學 >> Excel 綜合

VBA 完整操作儲存格批註:讀取、自動記錄修改歷程、切換顯示模式、調整大小

VBA 全方位控制 `Comment` 物件:讀取文字、資料變更自動記錄修改者/時間、切換批註指示器模式、設定批註框尺寸。

1. 讀取批註文字

Dim str As String
str = WorksheetFunction.Clean(Range("A1").Comment.Text)
MsgBox str

`Clean` 移除特殊字元。若儲存格無批註會報錯,需錯誤處理。

2. 資料修改自動添加批註記錄

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim cell As Range, oldTxt As String, newTxt As String
    For Each cell In Target
        With cell
            On Error Resume Next
            oldTxt = .Comment.Text
            If Err <> 0 Then .AddComment
            newTxt = oldTxt & " Changed by " & Application.UserName & " at " & Now & vbLf
            .Comment.Text Text:=newTxt
            .Comment.Visible = True
            .Comment.Shape.Select
            Selection.ShapeRange.AutoSize = True
            .Comment.Visible = False
        End With
    Next
End Sub

3. 切換批註指示器三種模式

Sub ToggleComments()
    If Application.DisplayCommentIndicator = xlCommentAndIndicator Then
        Application.DisplayCommentIndicator = xlCommentIndicatorOnly
    Else
        Application.DisplayCommentIndicator = xlCommentAndIndicator
    End If
End Sub
  • `xlCommentAndIndicator`:永遠顯示批註文字與指示器。
  • `xlCommentIndicatorOnly`:懸停才顯示文字。
  • `xlNoIndicator`:完全隱藏。

4. 設定批註框固定尺寸

With Range("A1").Comment.Shape
    .Width = 150: .Height = 300
End With

舊版 `NoteText` 已棄用,統一用 `Comment` 物件。

copyright © 萬盛學電腦網 all rights reserved