簡體   English   中英

通過VBA根據單元格值向單元格添加注釋,然后在值更改時將其刪除

[英]Adding a comment to cell by VBA based on cell value then remove it on value change

我與工作中的多個同事共享一個工作簿,並嘗試在單元格J1中的某個時間段(選擇期間作為數字列表)中向單元格(F47)添加注釋。

如果期間= 8,我想添加注釋。 如果期間不等於8,我想刪除/隱藏注釋。

Sub Comment_Delete()

 Dim C As Comment

 Worksheets("Statement").Activate

 For Each C In ActiveSheet.Comments
  C.Delete
 Next

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

 Set Period = Range("J1")
 Set Target = Range("F47")

 If Period.Value = 8 Then
     Target.AddComment ("If balance is meant to be negative but = 0, the debtor was invoiced in P8 and balance was paid off, see data sheet P* Bal Paid")

 Else: Call Comment_Delete
 End If

 End Sub

如果我從消息(“ Application-Defined or Object-defined error”(應用程序定義的錯誤或對象定義的錯誤))中選擇了(J1),則會出現運行時1004錯誤,該錯誤突出顯示了以下代碼

Target.AddComment ("If balance is meant to be negative but = 0, the debtor was invoiced in P8 and balance was paid off, see data sheet P* Bal Paid")

您需要先清除所有現有注釋:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Set Period = Range("J1")
    Set Target = Range("F47")

    If Period.Value = 8 Then
        If Not Target.Comment Is Nothing Then Target.Comment.Delete
        Target.AddComment "If balance is meant to be negative but = 0"

    Else: Call Comment_Delete
    End If

End Sub

使用Worksheet_Change事件並監視J1可能會更好,除非其中包含公式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM