The way =IF function works in Excel, similarly If Else loop works in Excel VBA (Visual Basic for Applications).

This example gives an interface (an input box) to the user to enter details, based on which a reply is given by Excel VBA in the form of a message box.

You want to ask the user for his/her Name and Age.

  • If Age >= 18, the user is Eligible to Apply for a Driving license.
  • If Age <18, the user is Not Eligible.

Open VBE

You need to first open the VBE (Visual Basic Editor) using Alt + F11.

Double-click on the Sheet name (Sheet 1 in this case) in which you want to write your code.

VBE - Visual Basic Editor

VBE – Visual Basic Editor

The code for this example is

Code to check Driving Eligiblity

Code to check Driving Eligiblity

Understanding the Code

  • ‘ Driving Eligibility
    • the ‘ allows us to enter a comment in VBA.
    • this comment helps us to remember that the below code is written with the objective to check driving eligibility.
  • Sub ex7 ()
    • Whenever you start writing code in VBA, it always starts with ‘Sub’ and a name for your code.
    • ex7 is an example, you can write any name you like.
    • () has to be at the end of the name
  • Dim a As String
    • Defining a dimension with the name ‘a’ as String.
    • String holds textual data.
  • Dim b As Integer
    • Defining a dimension with the name ‘a’ As an Integer.
    • Integer holds number data.
  • a = InputBox (“Enter name”)
    • An InputBox will be displayed on the screen, asking the user for his/her Name.
    • Name will be stored in ‘a’.

      Enter Name in Input Box

      Enter Name in Input Box

  • b = InputBox (“Enter Age”)
    • An InputBox will be displayed on the screen, asking the user for his/her Age.
    • Age will be stored in ‘b’.

      Enter Age in InputBox

      Enter Age in InputBox

  • If b < 18, Then
    • Checking if the Value of ‘b’ < 18 or not.
  • MsgBox (“Sorry, apply later”)
    • If b < 18 = True, this message will appear in a MsgBox.
  • Else: MsgBox (“You are eligible to apply!”)
    • If b < 18 = False, this message will appear in a MsgBox.

      Result

      Result

  • End If
    • Always required to be put at the end of the If Else loop.
  • End Sub
    • Always required to be put at the end of the code.

Try out 1 more example!

If not eligible, also show after how many years can the user apply for a license?