在更改VBA之前捕获行号

时间:2017-11-28 12:00:46

标签: excel vba excel-vba

我刚开始编写VBA代码,我遇到了问题。如果我在单元格b11并切换到单元格a2c2,则代码无任何问题。但是,如果我在单元格b2中写入内容并按 Enter ,则代码不起作用。我认为这是因为ActiveCell.row。即使按 Enter

,如何才能使其正常工作?

P.S。我需要ActiveCell.Row,因此我可以在MsgBox错误中获取单元格编号。

Sub Change()

Dim i As Long

i = ActiveCell.Row

If (Cells(i, "B") + Cells(i, "D")) <> Cells(i, "F") Then
    MsgBox "B" & i & " + D" & i & " must equal cell F" & i & " which is: " & Range("W" & i).Value

    Cells(i, "B").Interior.Color = RGB(255, 0, 0)
    Cells(i, "D").Interior.Color = RGB(255, 0, 0)
Else
    Range(Cells(i, "B"), Cells(i, "D")).Interior.Color = RGB(1000, 1000, 1000)
End If

End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range("B11:F10000"), Range(Target.Address)) Is Nothing Then
   Call Change
End If

2 个答案:

答案 0 :(得分:1)

如果您希望修改单元格“B2”时代码有效,则需要在Worksheet_Change事件中修改扫描范围内的范围。

<强>代码

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Application.Intersect(Range("B11:F10000"), Target) Is Nothing Then
   Change Target.Row ' call change and pass the row number
End If

End Sub
Sub Change(i As Long)
' get the row number directly from the worksheet_change event

If (Cells(i, "B") + Cells(i, "D")) <> Cells(i, "F") Then
    MsgBox "B" & i & " + D" & i & " must equal cell F" & i & " which is: " & Range("W" & i).Value

    Cells(i, "B").Interior.Color = RGB(255, 0, 0)
    Cells(i, "D").Interior.Color = RGB(255, 0, 0)
Else
    Range(Cells(i, "B"), Cells(i, "D")).Interior.Color = RGB(1000, 1000, 1000)
End If

End Sub

答案 1 :(得分:0)

请重新开始并确保您的事件处理程序正常工作。在空工作表中添加此项以尝试。

Public Sub Worksheet_Change(ByVal Target As Range)
    MsgBox "You just changed " & Target.Address
End Sub

请注意,此事件处理程序必须位于此工作表的私有模块中:

enter image description here

更多信息: http://www.ozgrid.com/VBA/run-macros-change.htm