通过基于单元格值的VBA向单元添加注释,然后在值更改时将其删除

我在工作中与多个同事共享工作簿,并试图在单元格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 

我得到一个运行时1004错误,如果我select(J1)的消息“应用程序定义或对象定义的错误”,其中突出显示下面的代码

 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可能会更好 – 除非包含公式。