获取VBA中Cell Change的行号

时间:2016-06-19 06:47:40

标签: excel vba excel-vba

我知道如何检查列是否已更改,如此

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("H5")) Is Nothing Then 
        'Pop up a message saying H5 has changed
    End If
End Sub

如果我想要在同一行上更改另一列,我可以这样做

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("H5")) Is Nothing Then 
        Range("A5").Value = "Look at me!"
    End If
End Sub

现在如果我想实现上述目标,但是对于row1范围内的所有列到表尾?这样的事情(注意,我知道这不起作用)

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("H1:H")) Is Nothing Then 
        Range("A" & Target.row).Value = "Look at me!"
    End If
End Sub

1 个答案:

答案 0 :(得分:5)

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("H:H")) Is Nothing Then 
        Range("A" & Target.row).Value = "Look at me!"
    End If
End Sub

虽然您应该注意,如果在同一操作中更新了多个单元格,则Target可以是多单元格范围。

这可能更安全:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim c As Range
    For Each c in Target.Cells
        If Not Intersect(c, Range("H:H")) Is Nothing Then
            '3 ways to accomplish the update 
            Range("A" & c.Row).Value = "Look at me!"
            c.EntireRow.Cells(1).Value = "Look at me!"
            Cells(c.Row, 1).Value = "Look at me!"
        End If
    Next c
End Sub