VBA根据单元格值向单元格添加注释,然后在值更改时将其删除

时间:2015-12-30 10:17:39

标签: excel vba excel-vba

我在工作中与多位同事共享一本工作簿,并试图在单元格J1中的某个时间段(选择句点作为数字列表)中向单元格(F47)添加注释。

如果Period = 8,我想添加评论。 如果期间没有&= t = 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

如果我选择关闭(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")

1 个答案:

答案 0 :(得分:3)

您需要先清除任何现有评论:

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