Search code examples
vbaexcelif-statementmsgbox

Excel VBA IF then IF statement


I am using an "If Then If msgbox vbYesno" Statement and I am not sure how to get out correctly of it (I know Goto is not clean).

Can someone tell me what my mistake is? I did not find anyone using something similar.

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

Solution

  • You can leave your procedure if you're not going to "jump", jumping otherway:

    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
    

    Another option is use boolean variable:

    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