Control Structure and Condition
Decision making in VBA(Conditions)
Decision making or conditions are foundation of any
programming language. It helps to execute code on the basis of various
conditions. Conditional statements mainly execute True statement in the code. VBA
provides two main structures for making decisions and carrying out alternative
processing, represented by the If and Select Case statements. If is the more
flexible one, but Select Case is better when you are testing a single variable.
Given below are few conditions which mainly used in VBA
programming:
GoTo Statement:
A
GoTo statement offers the most straightforward means for changing a program’s flow.
The GoTo statement simply transfers program execution to a new statement, which
is preceded by a label. Your
VBA routines can contain as many labels as you like. A label is just a text
string followed by a colon. Jump
to a labeled statement. This is used mostly for error handling
On
Error GoTo Oops
'[your
code goes here]
Exit
Sub
Oops:
MsgBox
"An error occurred"
If-Then Statements:
Use
the If-Then structure when you want to execute one or more statements conditionally.
The optional Else clause, if included, lets you execute one or more statements
if the condition you’re testing is not true.
a) If – Then
Do something if a condition is true. Written as a single statement
If x = 1 Then y = 1
b) If – Then – End If
Do something if a condition is true. Can use multiple statements
If x = 1 Then
y = 1
z = 1
End If
c) If – Then – Else
do something if a condition is true; otherwise, do something else.
Written as a single statement
If x = 1 Then y = 1 Else y = 0
d) If – Then – Else – End If
Do something if a condition is true; otherwise, do something else. Can
use multiple statements
If x = 1 Then
y = 1
Z = 1
Else
y = 0
Z = 0
End If
Select
Case:
The
Select Case structure is useful for decisions involving three or more options
(although it also works with two options, providing an alternative to the
If-Then-Else structure). Do one of several things, depending on a condition
Select
Case x
Case 1
y = 1
Z = 1
Case Is > 1
y = 2
Z = 2
Case Else
y = 0
Z = 0
End
Select