IF Then Function

     

    Sub If_Condition_in_Single()
    If Range("H5").Value = 55 Then _ Range("H5").Interior.ColorIndex = 3
    End Sub

     

    IF Then - - - Else Function

     

  • Only one option is available
  •  

     

  • If Condtion is TRUE - - - "Then" value is executed
  • If Condtion is FALSE - - - "ELSE" value is executed
  •  

    If then - - - Else with RANGE

     

     

    Code

     

    Sub Finding_Result()
    If Range("B2").Value > 35 Then
    Range("C2").Value = "Pass"
    Else
    Range("C2").Value = "Fail"
    End If
    End Sub

     

    If then - - - Else with For Loop: Find the result pass\fail:

     

    Code

    Private Sub CommandButton1_Click()
    'Loop Variable
    Dim i As Integer
    'Value starts from Second row, hence loop value(i) has to start from 2
    For i = 2 To 7
    'cells value indicates (row index, Column index)
    If Cells(i, 2) > 35 Then
    Cells(i, 3) = "Pass" 'If condition is True
    Else
    Cells(i, 3) = "Fail" 'If condition is False
    End If
    Next
    End Sub

     

     

    Find the required row from Loop

     

    Private Sub CommandButton1_Click()
    'to print the dates
    'Dim i As Integer, j As Date
    'j = #1/1/2015#
    'For i = 1 To 15
    'Cells(i, 1).Value = j
    'j = j + 1
    'Next
    Dim max As Long
    max = Range("A" & Rows.Count).End(xlUp).Row
    For m = 1 To max
    If Cells(m, 1).Value = #1/6/2015# Then
    Cells(m, 1).Select
    Exit For
    End If
    Next
    MsgBox Selection.Row
    End Sub

     

    IF Then - - - Else If Function

     

  • Used to test more than one condition
  •  

     

  • IF Condition:
  • (i)Indicates about statement

    (ii)Condition is an expression which is a Numeric or String

     

  • Code 1 to n (Eles IF): Codes are executed when condition is TRUE
  • If we want to execute multiple conditions

     

  • Else Code: is executed when Condition is FALSE., This is optional
  • Note:Condition doesn't exists for ELSE code

     

    Example: Retrive Grade result against the marks of students:

     

  • Marks secured > 90 = Excellent
  • Marks secured > 70 = Very Good
  • Marks secured > 50 = Good
  • Marks secured > 35 = Pass
  • Marks secured < 35 = Fail
  •  

    Code:

     

    Sub Grading_of_Students()
    Dim i As Integer
    For i = 2 To 8
    If Cells(i, 2) > 90 Then
    Cells(i, 3) = "excellent"
    ElseIf Cells(i, 2) > 70 Then
    Cells(i, 3) = "Very Good"
    ElseIf Cells(i, 2) > 50 Then
    Cells(i, 3) = "Good"
    ElseIf Cells(i, 2) > 35 Then
    Cells(i, 3) = "Pass"
    Else
    Cells(i, 3) = "Fail"
    End If
    Next
    End Sub