0
votes

I use my code to auto add comments for each time edit cell content.
I would like to apply the code in range B2:E1000, but my code apply to all cells.
So how can I set the range? Thanks in advance.

Private Sub Worksheet_Change(ByVal Target As Range)  
Dim c As Range  
Dim ws As Worksheet  
ActiveSheet.Cells.RowHeight = 25  

For Each c In Target  
    If c.Comment Is Nothing And c.Value <> "" Then  
        With c.AddComment  
            .Visible = False  
            .Text Application.UserName & "-" & Date & " " & c.Value  
            .Shape.TextFrame.AutoSize = True  
        End With  
    ElseIf Not c.Comment Is Nothing And c.Value <> "" Then  
        c.Comment.Text Application.UserName & "-" & Date & " " & c.Value & vbNewLine & c.Comment.Text  
    End If  
Next  
End sub
2

2 Answers

1
votes

Use Intersect functionn, Updated code :

Private Sub Worksheet_Change(ByVal Target As Range)  
        Dim c As Range  
        Dim ws As Worksheet
        dim rng As Range  

        Set rng = Range("B2:E1000")

        If Intersect(Target, rng) Is Nothing Then Exit Sub

        ActiveSheet.Cells.RowHeight = 25  

        For Each c In Target  
            If c.Comment Is Nothing And c.Value <> "" Then  
                With c.AddComment  
                    .Visible = False  
                    .Text Application.UserName & "-" & Date & " " & c.Value  
                    .Shape.TextFrame.AutoSize = True  
                End With  
            ElseIf Not c.Comment Is Nothing And c.Value <> "" Then  
                c.Comment.Text Application.UserName & "-" & Date & " " & c.Value & vbNewLine & c.Comment.Text  
            End If  
        Next  
    End sub
0
votes

You can use the Intersect Statement for this:

Set isect = Application.Intersect(Range("B2:E1000"), Target)

Your code would the look like this:

Private Sub Worksheet_Change(ByVal Target As Range)  
Dim c As Range  
Dim ws As Worksheet  
ActiveSheet.Cells.RowHeight = 25  

Set isect = Application.Intersect(Range("B2:E1000"), Target)

If Not isect Is Nothing Then
For Each c In Target  
    If c.Comment Is Nothing And c.Value <> "" Then  
        With c.AddComment  
            .Visible = False  
            .Text Application.UserName & "-" & Date & " " & c.Value  
            .Shape.TextFrame.AutoSize = True  
        End With  
    ElseIf Not c.Comment Is Nothing And c.Value <> "" Then  
        c.Comment.Text Application.UserName & "-" & Date & " " & c.Value & vbNewLine & c.Comment.Text  
    End If  
Next  
end if
End sub