工作表更改事件 - 检查列中的单元格是否存在百分比差异



我正在努力让一个Worksheet_Change事件工作,目的是检查范围 G12:42 和范围 J12:42 之间的百分比差异是否大于 10%。我在 G12:42 范围内有一个计算,这似乎让我有些头疼。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim diffPercent
    'Check that the data is changed between row 12 and 42 and it is even row. eg 12,14,16...42.
    If (Target.Row > 12 And Target.Row < 42) And ((Target.Row Mod 2) = 0) Then  'And _
            '(Target.Column = 7 Or Target.Column = 10) Then
        'Get the values in J ang G columns of that particular row.
        number1 = Range("G" & Target.Row).Value
        number2 = Range("J" & Target.Row).Value
        'Check for presence of both the inputs to calculate difference in percentage.
        If Not chkInputs(number1, number2) Then
            Exit Sub
        End If
        'Calculate the percentage difference.
        diff = number2 - number1
        diffPercent = (diff / number2) * 100
        'Give alert if difference more than 10 percent
        If diffPercent > 10 Then
            MsgBox "Oppps. Your system is not working!"
        End If
    End If
End Sub
Function chkInputs(number1, number2)
chkInputs = False
If IsNumeric(number1) And IsNumeric(number2) Then
    chkInputs = True
End If
End Function

预期结果是触发提供消息的消息框。

不需要单独的功能。您可以将其包含在主代码中。还可以使用 Intersect 来处理相关范围,否则如果该行范围中的任何位置发生更改,代码将触发。还有一件事。检查 J 列中的单元格是否未0否则您将收到溢出错误。

您可能还想查看使用Worksheet_Change

这是您正在尝试的(未经测试(吗?

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rngToCheck As Range
    Dim NumA As Variant, NumB As Variant
    Dim i As Long
    On Error GoTo Whoa
    '~~> Set the relevant range
    Set rngToCheck = Union(Range("G12:G42"), Range("J12:J42"))
    Application.EnableEvents = False
    If Not Intersect(Target, rngToCheck) Is Nothing Then
        For i = 12 To 42 Step 2 '<~~ Loop through only even rows
            NumA = Range("G" & i).Value
            NumB = Range("J" & i).Value
            If IsNumeric(NumA) And IsNumeric(NumB) And NumB <> 0 Then
                If ((NumA - NumB) / NumB) * 100 > 10 Then
                    MsgBox "Please check the value of Col G and J Cells in row " & i
                    Exit For
                End If
            End If
        Next i
    End If
Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

相关内容

最新更新