当范围内的单元格更改并满足给定条件时,显示Excel VBA消息框

时间:2012-09-14 14:48:02

标签: excel vba excel-vba

我需要一些帮助来创建Excel VBA,以便在计算单元格(包含公式的单元格)的任何输入范围发生变化并满足范围的给定条件时显示消息框。

例如,范围“B2”包含计算的单元格,它们是“A2”的函数,如果在更新输入时“A2”,重新计算的单元格,“B2”超过20%,我想发出警告带有消息框的用户。

3 个答案:

答案 0 :(得分:1)

编辑:Scott提醒我Intersect函数比这个InRange函数效果更好

Edit2:这将允许您对不同的范围有不同的规则。如果用户更改的单元格在您的一个受控范围内,则调用该范围的验证规则。否则该功能继续。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim Range1 As Range, Range2 As Range '...
    Set Range1 = Me.Range("A1:A9")
    Set Range2 = Me.Range("B1:B9")
    '...

    If Not intersect(Range1, Target) Is Nothing Then
        'Rule for Range1
        If Target.Value > 0.2 Then   'put your condition here
            MsgBox "You exceeded 20%"
        End If

    ElseIf intersect(Range2, Target) Is Nothing Then
        'Rule for Range2...
    'elseif more ranges...
         'More rules...
    End If

End Sub

答案 1 :(得分:1)

<强>更新

此代码仅在您的输入单元格发生更改时触发,这比仅使用“Worksheet_Calulate”更好:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim myRange As Range

myRange = Range("B1:B2") '-> assumes input cells are in B1:B2

If Intersect(myRange, Target) Then

    '-> assumes calculated cell in A1
    If Range("A1").Value > 0.2 Then MsgBox "Above 20%"

    '-> to loop through many cells, do this
    Dim cel As Range
    For Each cel In Range("A1:A10")

        If cel.Value > 0.2 Then MsgBox cel.Address & " Above 20%"
        Exit For

    Next

End If

End Sub

答案 2 :(得分:0)

以下是使用检查工作表1中A1单元格更改的工作簿工作表更改事件的示例

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
On Error Resume Next
    'check to ensure we are working in the correct Sheet
    If ActiveWorkbook.ActiveSheet.Name = "Sheet1" Then
        'check to see how many cells have been targeted
        If Target.Cells.Count = 1 Then
            If Target.Cells.Address = "$A$1" Then
                'check to see what value has been entered into the cell
                If Target.Value = 20 Then
                    MsgBox "Alerting the user"
                End If
            End If
        End If
    End If
End Sub