Microsoft Access VBA Macro Programming

(Tina Sui) #1

You can put in severalAnds orOrs within the condition, although it gets complicated
with more than three. It all depends on what you are trying to achieve in your decision
statement and what the procedure is trying to do. You may be writing something very simple
such asIf x=1 Then, or you may be working on a more complicated conditional statement.


Select Case Statements


Another statement available in VBA for conditional processing is theSelect Casestatement.
If you have a variable and you want different actions to occur depending on the value of that
variable, you can use a series of If statements as follows:


If x=1 then MsgBox "x=1"
If x=2 then MsgBox "x=2"
If x=3 then MsgBox "x=3"


However, this is a good example of where aSelect Casestatement makes the code much
cleaner:


x = 23
Select Case (x)


Case ( 1 )
MsgBox "x=1"
Case ( 23 )
MsgBox "x=23"

End Select


TheSelect Casestatement provides a simple means to interrogate a specified variable and
take action accordingly. The statementSelect Case (x)defines the variable to be interrogated
asxand is the start of the block of code for this procedure.Case (1)gives the action for if the
value is 1—show a message box showing “x=1.”Case (23)gives the action for if the value is
23—show a message box showing “x=23.” Becausexhas been set to 23 at the start of the
code, the message box will show “x=23.”
You can also include the statementsToandIsin theCasestatement:


Sub Test_Case (Grade)
Select Case Grade
Case 1
Msgbox "Grade 1 "
Case 2, 3
Msgbox "Grade 2 or 3 "
Case 4 To 6
Msgbox "Grade 4, 5 or 6 "


Chapter 4: Programming Basics: Decisions and Looping 39

Free download pdf