VBA for Excel 2007 tutorial-Conditional Statements


VBA Conditional Statements

Most of programs involve making decisions. Making decision is to check whether a given condition is true. Then one or more statements will be executed based on the checked result. In VBA, to make a decision you can use if and select case statements.

-If statement

Syntax 1:
 
  If condition Then

              do something
  End if
 
  Example:
  Dim x As Integer
  x=InputBox(“Enter a value:”)
  If x mod 2=0

              Msgbox “x is an even number.”
  End if
 

Syntax 2:
 
  If condition Then

              do something
  Else

            do something
  End if
 
  Example:
  Dim x As Integer
  x=InputBox("Enter a value:")
  If x mod 2=0

              Msgbox "x is an even number."
  Else        Msgbox "x is an odd number."
  End if
 

Syntax 3:
  If condition Then

              do something
  ElseIf condition then

             do something     Else

              do something
   End if
 
  Example:
  Dim x As Integer
  x=InputBox("Enter a value:")
  If  x>0

              Msgbox "x is a positive number."
  ElseIf x<0

              Msgbox "x is a negative number."
  Else          Msgbox "x is equal to zero."
  End if
  -Select case: It is used to check multiple choices. The select case statement has the following syntax:
  Select case variable

     case con1: do something

     case con2: do something
 
  ….
         case else: do something
  End select
 
  Example:
 

Dim x As Integer

Dim g As String

x =InputBox("Enter score:")

Select Case x

    Case Is >= 90

        g = "A"

    Case Is >= 85 And x < 90

        g = "B+"

    Case Is >= 75 And x < 85

        g = "B"

    Case Is >= 65 And x < 75

        g = "C+"

    Case Is >= 55 And x < 65

        g = "C"

    Case Is >= 50 And x < 55

        g = "D"

    Case Else

        g = "F"

End Select

MsgBox g


Comments





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.