如果条件满足运行宏

时间:2018-01-19 03:22:01

标签: excel-vba if-statement vba excel

给定单元格A1 = A,单元格A2 = B. 我有一个VBA代码 如果A = B值如果为true则不执行任何操作(或运行null宏) 如果Flase值:它将自动触发一个宏 请帮助任何人

1 个答案:

答案 0 :(得分:0)

如果手动输入A1和A2而不是基于公式的计算,那么以下内容应该有效:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
    'declare and set your worksheet, amend as required
    If Target.Address = "$A$1" Or Target.Address = "$A$2" Then
        If ws.Range("A1") <> ws.Range("A2") Then MyMacro
    End If
End Sub

Sub MyMacro()
    MsgBox "It works!", vbInformation, "Title"
End Sub

如果根据公式计算A1和A2,则应执行以下操作:

Private Sub Worksheet_Calculate()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
    'declare and set your worksheet, amend as required
    If ws.Range("A1") <> ws.Range("A2") Then
        MyMacro
    End If
End Sub

Sub MyMacro()
    MsgBox "It works!", vbInformation, "Title"
End Sub