Nested IF In Visual Basic

96 Views Asked by At

I want to make a program that "Loan will be accepted if Earns over 30k & on the job for more than 2 years or been on the job for more than 5 years. and age between 30 - 50.

But doesn't working

If sngSalary > 30000 Then
    If sngAge < 50 Then
        If sngYear > 5 Then
            lblMessage.Text = "Application qualifies"
        Else
            lblMessage.Text = "Application does not qualifies"
        End If
    Else
         If sngYear >= 2 Then
            lblMessage.Text = "Application qualifies"
         Else
            lblMessage.Text = "Application does not qualifies"
         End If
    End If
Else
    If sngAge > 30 Then
         If sngYear > 5 Then
             lblMessage.Text = "Application qualifies"
         Else
             lblMessage.Text = "Application does not qualifies"
         End If
    Else
         If sngYear >= 2 Then
             lblMessage.Text = "Application qualifies"
         Else
             lblMessage.Text = "Application does not qualifies"
         End If
    End If
End If
2

There are 2 best solutions below

0
On

Just code it up almost exactly like you said in your description:

Private Sub Test()
   If (sngSalary > 30000 And sngYear > 2) Or (sngYear > 5 And sngAge >= 30 And sngAge <= 50) Then
      lblMessage.Text = "Application qualifies"
   Else
      lblMessage.Text = "Application does not qualifies"
   End If
End Sub
2
On

Quite often complex logic can be simplified by moving the code to a function and revising the logic so that the function is left early if a criteria is not met. In writing such a function I try to keep the logic retricted to simple yes/no gates.

The expression of the required conditions by the OP is quite confused so the code below may not be correct, but it does demonstrate the principle.

Option Explicit

Public Function IsEligible(ByVal ipSalary As Long, ByVal ipAge As Long, ByVal ipEmploymentTime As Long) As String

    IsEligible = "Application does not qualify"
    If ipEmployment < 2 Then Exit Function
    
    If ipSalary < 30000
    
        If ipEmploymentTime < 5 Then Exit Function
        If ipAge < 30 Then Exit Function
        If ipAge > 50 Then Exit Function
    
    End If
    
    IsEligible = "Application qualifies"
    
End Function