Using the IF statement in VB Access:

In this example, I designed a new form and set up a message textbox which I called txtMsg.

I then set up a command button called cmdChkGoal which I will use to check the goal and see if it is less than 200000.

I then went to the click event for the command button cmdChkGoal and chose the Build Code option. When the code for the subroutine was shown, I entered the IF statement to test and see if the goal was less than 200000. If it was, I displayed the message Goal too low! in txtMsg, IF it was not, I displayed the message Goal okay for this year! in txtMsg. This was done by assigning the literal to the textbox.

THE CODE IS:

If Goal < 200000 Then

txtMsg = "Goal too low!"

Else

txtMsg = "Goal okay for this year!"

End If


Now I am going to add two buttons to calculate a new goal based on asking a series of questions. The questions are written such that if you get a yes to one question, you will not check the others.

The form and the code behind the click events for these three command buttons is shown below. Notice that the calculation of the new goal is done with the IF...ELSE and the IF...ELSEIF.

 Option Compare Database   
 Option Explicit   

  Private Sub cmdCalcNewGoal_Click()   
      If YTDTotal > Goal Then   
         txtMsg = "This year ahead of goal!"   
         txtNewGoal = Val(Goal * 1.15)   
      ElseIf LastYrTotal > Goal Then   
         txtMsg = "Last year ahead of goal!"   
         txtNewGoal = Val(Goal * 1.1)   
      ElseIf YTDTotal > LastYrTotal Then   
         txtMsg = "This year ahead of last year!"   
         txtNewGoal = Val(Goal * 1.05)   
      Else   
         txtMsg = "Have to work harder!"   
         txtNewGoal = Val(Goal)   
      End If   
  End Sub   

  Private Sub cmdChkGoal_Click()   
      If Goal < 200000 Then   
         txtMsg = "Goal too low!"   
      Else   
         txtMsg = "Goal okay for this year!"   
      End If   
         
  End Sub   

 Private Sub cmdOtherCalc_Click()

 If YTDTotal > Goal Then
        txtMsg = "This year ahead of goal!" 
        txtNewGoal = Val(Goal * 1.15)   
    Else   
        If LastYrTotal > Goal Then   
           txtMsg = "Last year ahead of goal!"   
           txtNewGoal = Val(Goal * 1.1)   
        Else   
           If YTDTotal > LastYrTotal Then   
              txtMsg = "This year ahead of last year!"   
              txtNewGoal = Val(Goal * 1.05)   
           Else   
             txtMsg = "Have to work harder!"   
             txtNewGoal = Val(Goal)   
           End If   
        End If   
     End If   
 End Sub   

The message box that appears above is associated with the Check Goal command button. The code that generated this box is shown below:

Private Sub cmdChkGoal_Click()
    If Goal < 200000 Then
       txtMsg = "Goal too low!"
       MsgBox ("Goal too low!")
    Else

txtMsg = "Goal okay for this year!" End If

End Sub
>