vba - 当行数变化时使用worksheet_calculate

标签 vba excel

我在 x 列和 y 列中有一系列数据:

image of data in column x and 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/

相关文章:

vba - 1004 错误 "Is it possible it was moved, renamed or deleted?"

excel - 将来自不同Excel工作簿的数据收集到一个工作簿中

regex - 匹配字符串vba excel中的日期模式

javascript - 从 VBA 调用 JavaScript 文件

Excel、IF 更大函数、时间/日期偏移

vba - 在邮件正文中发送图表

excel - 使用 "ADODB.Stream"将ANSI转为UTF-8,第一行漏掉1-2个字符

Excel 2016 升级导致内存崩溃

ms-access - Access Report 不允许我引用 VBA 中的字段,除非它本身就在报告中

excel - 在没有复制和粘贴的情况下使用左侧