If-Then Constructs

If-Then constructs


The most commonly used instruction grouping in VBA. The basic syntax of the If-then construct is:

[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]
If condition then true_instructions [Else false_instructions]
[/sourcecode]


If-Then Without Else

[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]

Sub GreetMe1()
If Time < 0.5 Then MsgBox "Good Morning"
End Sub

Sub GreetMe1a()
If Time < 0.5 Then
MsgBox "Good Morning"
End If
End Sub

Sub GreetMe2()
If Time < 0.5 Then MsgBox "Good Morning"
If Time >= 0.5 Then MsgBox "Good Afternoon"
End Sub
[/sourcecode]


If-Then with Else

[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]
Sub GreetMe3a()
If Time < 0.5 Then
MsgBox "Good Morning"
‘Other Statements go here
Else
MsgBox "Good Afternoon"
‘Other Statements go here
End If
End Sub

Sub GreetMe4()
If Time < 0.5 Then MsgBox "Good Morning"
If Time <= 0.5 And Time < 0.75 Then MsgBox “Good Afternoon”
If Time <= 0.75 Then MsgBox "Good Evening"
End Sub
[/sourcecode]


If-Then that exits superfluous conditions (faster)

Construct

[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]
If condition Then
[true_instructions]
[ElseIf condition-n Then
[alternate_instructions]]
[Else
[default_instructions]]
End If

Sub GreetMe5()
If Time < 0.5 Then
MsgBox "Good Morning"
ElseIf Time >= 0.5 And Time < 0.75 Then
MsgBox "Good Afternoon"
Else
MsgBox "Good Evening"
End If
End Sub
[/sourcecode]


Nested If-Then constructs

[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]
Sub GreetMe6() ‘Most efficient use of if-then
If Time < 0.5 Then
MsgBox "Good Morning"
Else
If Time <= 0.5 And < 0.75 Then
MsgBox "Good Afternoon"
Else
If Time >= 0.75 Then
"Good Evening"
End If
End If
End If
End Sub
[/sourcecode]


If statement which always executes

[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]
Sub Discount1() ‘the If always executes, but the right answer comes up
Dim Quantity As Variant
Dim Discount As Double

Quantity = InputBox(“Enter Quantity: “)

If Quantity = "" Then Exit Sub
If Quantity >= 0 Then Discount = 0.1
If Quantity >= 25 Then Discount = 0.15
If Quantity >= 50 Then Discount = 0.2
If Quantity >= 75 Then Discount = 0.25
MsgBox "Discount: " & Discount
End Sub

Sub Discount2()
Dim Quantity As Variant
Dim Discount As Double

Quantity = InputBox("Enter Quantity: ")

If Quantity = "" Then Exit Sub
If Quantity >= 0 And Quantity < 25 Then
Discount = 0.1
ElseIf Quantity < 50 Then
Discount = 0.15
ElseIf Quantity < 75 Then
Discount = 0.2
Else
Discount = 0.25
End If
MsgBox "Discount: " & Discount
End Sub
[/sourcecode]