简体   繁体   中英

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

I share a workbook with multiple colleagues at work and am trying to add a comment to a cell (F47) in a certain period (Period is selected as a list of numbers) in cell J1.

If the Period = 8 i want to add the comment. And if the Period doesn't = 8 I want to remove/hide the comment.

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

I get a Runtime 1004 Error if i select off of (J1) with the message "Application-Defined or Object-defined error" Which Highlights the code below

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")

You need to clear any existing comment first:

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

You'd probably be better off using a Worksheet_Change event and monitoring J1 - unless that contains a formula.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM