简体   繁体   中英

Nested If Statement not Returning Correct Message in VBA

I am trying to have this VBA code execute checks on a sheet to make sure that first the always required cells are not empty(H6,X6,AH6,J8), then check for the TER code in cell AN8 if it is found I then want the additional cells (AA19,AA20 and J28) to be checked if they are empty. I have this code on sheet1, and have it setup to executed upon saving. I'm not getting any errors but this code keeps displaying my second msgbox of "A required field for a termination is missing..." even when TER is not found in cell AN8. What am I missing?

Sub CheckRequired()
    Dim celltxt As String
    celltxt = Sheet1.Range("AN8").Text

    If (Range("H6") = Empty) Or (Range("X6") = Empty) Or (Range("AH6") = Empty) Or (Range("J8") = Empty) Then
        MsgBox " A required field has not been populated, please enter the missing information in the highlighted field and save again. "
    ElseIf InStr(1, celltxt, "TER") Then
    ElseIf (Range("AA19") = Empty) Or (Range("AA20") = Empty) Or (Range("J28") = Empty) Then
        MsgBox " A required field for a Terminiation is missing, check highlighted required fields."
    Else
        MsgBox " The personnel change form has been successfully completed! "
    End If
End Sub

Could you engineer the code in a way similar to this?

Sub CheckRequired()
    Dim celltxt As String
    celltxt = Sheet1.Range("AN8").Text

    If (Range("H6") = Empty) Or (Range("X6") = Empty) Or (Range("AH6") = Empty) Or (Range("J8") = Empty) Then
        MsgBox " A required field has not been populated, please enter the missing information in the highlighted field and save again. "
        Exit Sub
    End If

    If InStr(1, celltxt, "TER") Then
        If (Range("AA19") = Empty) Or (Range("AA20") = Empty) Or (Range("J28") = Empty) Then
            MsgBox " A required field for a Terminiation is missing, check highlighted required fields."
            Exit Sub
        End If
    End If

    MsgBox " The personnel change form has been successfully completed! "

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM