在更改VBA之前捕获行号
我刚开始写VBA
代码,我面临一个问题。 代码工作没有任何问题,即如果我在单元格b11
切换到单元格a2
或c2
。 但是,如果我在单元格b2
写入一些内容并按Enter键 ,则代码不起作用。 我认为这是因为ActiveCell.row
发生的。 即使按Enter键 ,我怎样才能使它正常工作呢?
PS我需要的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
如果要在修改单元格“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
请重新开始,并确保您的事件处理程序正常工作。 将其添加到一个空的工作表来尝试。
Public Sub Worksheet_Change(ByVal Target As Range) MsgBox "You just changed " & Target.Address End Sub
请注意,这个事件处理器必须驻留在这个工作表的私有模块中:
更多信息在这里: http : //www.ozgrid.com/VBA/run-macros-change.htm