Excel VBA IF then IF 语句

Excel VBA IF then IF statement

我正在使用 "If Then If msgbox vbYesno" 语句,但我不确定如何正确地退出它(我知道 Goto 不干净)。

谁能告诉我我的错误是什么?我没有发现任何人使用类似的东西。

Sub IF_THEN_IF()

If Sheet1.Range("A1").Value > 500 Then
    If MsgBox("A1 > 500, Is this correct", vbYesNo, "Amount of Lines") = vbYes Then
        Range("H11").FormulaR1C1 = "My Formula"
    Else
        GoTo Jump
    End If
Else

Jump:    
    Range("H11").FormulaR1C1 = "I have Jumped"

End If

End Sub

一个可能的选择是这样的:

Sub IfThenElse()

    With Sheet1
        If .Range("A1").value > 500 Then
            If MsgBox("A1 > 500, Is this correct", vbYesNo, "Amount of Lines") = vbYes Then
                .Range("H11") = "My Formula"
            Else
                .Range("H11") = "I have Jumped"
            End If
        Else
            .Range("H11") = "I have Jumped"
        End If
    End With

End Sub

您有两个嵌入式 if。就这样。在 @Scott Holtzmann, you may see how to avoid writing "I have jumped" twice, by following the DRY method.

的回答中

此回答是对您对Vityaya回答的评论的回应。

Jump 中的代码转换为子例程,并在需要时调用它。

Sub IF_THEN_IF()

With Sheet1 

    If .Range("A1").Value > 500 Then

        Dim res as Variant
        res = MsgBox("A1 > 500, Is this correct", vbYesNo, "Amount of Lines")

        If res = vbYes Then
            .Range("H11").FormulaR1C1 = "My Formula"
        Else
            Jump
        End If

    Else   

        Jump

    End If

End Sub

Sub Jump()
   'code here
End Sub

您可以使用 AND 运算符

Sub IF_THEN_IF()    
If Sheet1.Range("A1").Value > 500 And _
   MsgBox("A1 > 500, Is this correct", vbYesNo, "Amount of Lines") = vbYes Then

    Range("H11").FormulaR1C1 = "My Formula"

Else

    Range("H11").FormulaR1C1 = "I have Jumped"

End Sub

如果你不打算"jump",你可以离开你的程序,跳到其他地方:

Sub IF_THEN_IF()
    If Sheet1.Range("A1").Value > 500 Then
        If MsgBox("A1 > 500, Is this correct", vbYesNo, "Amount of Lines") = vbYes Then
            Range("H11").FormulaR1C1 = "My Formula"
            Exit Sub
        End If
   End If
   'Jump
    Range("H11").FormulaR1C1 = "I have Jumped"
End Sub

另一种选择是使用布尔变量:

Sub IF_THEN_IF()
    Dim Jump as Boolean
    Jump = Sheet1.Range("A1").Value <= 500
    If Not Jump Then Jump = MsgBox("A1 > 500, Is this correct", vbYesNo, "Amount of Lines") <> vbYes
    If Jump Then
        Range("H11").FormulaR1C1 = "I have Jumped"
    Else
        Range("H11").FormulaR1C1 = "My Formula"
    End If
End Sub