我在 x 列和 y 列中有一系列数据:
我想比较 x 列和 y 列,并在 x > 2y 时发出通知。这是代码:(P.S.此代码运行完美)。
Private Sub Worksheet_Calculate()
If Range("A2").Value <> PrevValb Then
PrevValb = Range("A2").Value
If Range("A2").Value > 2 * Range("B2").Value Then
Dim result1 As VbMsgBoxResult
result1 = MsgBox("A2 has exceeded range", vbOKCancel, "Range Exceeded")
If result1 = vbCancel Then
Stop
End If
End If
End If
If Range("A3").Value <> PrevValc Then
PrevValc = Range("A3").Value
If Range("A3").Value > 2 * Range("B3").Value Then
Dim result2 As VbMsgBoxResult
result2 = MsgBox("A3 has exceeded range", vbOKCancel, "Range Exceeded")
If result2 = vbCancel Then
Stop
End If
End If
End If
If Range("A4").Value <> PrevVald Then
PrevVald = Range("A4").Value
If Range("A4").Value > 2 * Range("B4").Value Then
Dim result3 As VbMsgBoxResult
result3 = MsgBox("A4 has exceeded range", vbOKCancel, "Range Exceeded")
If result3 = vbCancel Then
Stop
End If
End If
End If
If Range("A5").Value <> PrevVale Then
PrevVale = Range("A5").Value
If Range("A5").Value > 2 * Range("B5").Value Then
Dim result4 As VbMsgBoxResult
result4 = MsgBox("A5 has exceeded range", vbOKCancel, "Range Exceeded")
If result4 = vbCancel Then
Stop
End If
End If
End If
End Sub
但是行数每天都会变化,单元格值(A2、A3、A4、A5)也会变化。我为 x 列和 y 列中的所有值创建了一个 NamedRange。有没有办法使单元格值动态化?我想使用带有整数的循环,其中每个整数引用行号,并且循环继续直到到达最后一行。但我不确定如何将其与现有代码结合起来。
如果您需要任何说明,请告诉我。
最佳答案
您需要从最后一行开始循环代码,如下所示:
Private Sub Worksheet_Calculate()
Dim rangeName As String
rangeName = "NamedRange"
firstRowNamedRange = Range(rangeName).Row
lastRowNamedRange = Range(rangeName).Row + Range(rangeName).Rows.count
For i = firstRowNamedRange To lastRowNamedRange Step 1
If Range("A" & i).Value <> PrevValb Then
PrevValb = Range("A" & i).Value
If Range("A" & i).Value > 2 * Range("B2" & i).Value Then
Dim result1 As VbMsgBoxResult
result1 = MsgBox("A" & i & " has exceeded range", vbOKCancel, "Range Exceeded")
If result1 = vbCancel Then
Stop
End If
End If
End If
Next i
End Sub
关于vba - 当行数变化时使用worksheet_calculate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50850323/