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

时间:2019-04-24 05:19:51

标签: excel vba

我正在努力获取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

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

1 个答案:

答案 0 :(得分:0)

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

您可能还希望看到Working with 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