Sunday, September 19, 2010

Conditional Statements

The use of conditional statement elements of programming is making decisions based on inputs. Below are type of conditional statements uses in VBA.

The If statement (single line)
If  x < 10 then Then MsgBox "The value of x is less than 10"
The If statement (multiple line)
If  x < 10 then Then
     Range ("A1")  =  x
     MsgBox "The value of x is less than 10"
End If


The If with elseif statement
Multiple ElseIf statements within an If block as shown by the following:

If condition Then
   ' Do something
ElseIf condition Then
   ' Do something
ElseIf condition Then
   ' Do something
Else
  ' Do something
End If


The Select Case statement
The following Select Case statement compares the current time against a list of literal times to determine which message to display:

Dim str As String
Select Case Time
   Case Is > #10:00:00 PM#
     str = "Bed time!"
   Case Is > #7:00:00 PM#
     str = "Time to relax."
   Case Is > #1:00:00 PM#
     str = "Work time."
   Case Is > #12:00:00 PM#
     str = "Lunch time!"
   Case Else
     str = "Too early!"
End Select
MsgBox str


Select statements are evaluated from the top to down. Select exits when program find the match.

The Switch statement
The Switch statement is similar to Select, but rather than executing statements, Switch returns a value based on different conditions. The following code is equivalent to the preceding example, except it uses Switch rather than Select:

Dim str As String
str = Switch(Time > #10:00:00 PM#, "Bed time!", _
            Time > #7:00:00 PM#, "Time to relax.", _
            Time > #1:00:00 PM#, "Work time.", _
            Time > #12:00:00 PM#, "Lunch time!", _
            Time >= #12:00:00 AM#, "Too early!")
MsgBox str

1 comment:

Please add if your have better information.