Implementing Branching with lfThen

Now that you know how to execute repetitive blocks of code, you need to know how to implement branching in your code. Branching is the process of selectively executing certain blocks of code depending on the value of an expression.

You use the If.. .Then statement to implement branching. The simplest form of the If.. .Then statement tests a single expression and executes a single statement if the expression is true. An example of a simple If.. .Then is shown here:

If sLetter = "A" Then rg.Font.Bold = True

If you need to execute multiple statements when a particular expression is true, then you can use the If.. .End If variation. Here's an example:

If CurrentDate > PaymentDueDate Then AmtDue = AmtDue + LateFee rgCustomer.Interior.Color = vbRed End If

Another variation on If.. .Then is the If.. .Then.. .Else.. .End If variation. This form allows you to execute one or more statements if the expression is true and one or more statements if the expression is false. For example, consider the following small block of code. This small fragment provides an example of how you might use If.. .Then to decide what to do with the response the user provides to a MsgBox function.

nResponse = MsgBox("Finished processing. Process another?", vbYesNo)

If nResponse = vbYes Then

OpenNextFile ' mythical ProcessNextFile Else

CloseCurrentFile ShutdownApp End If procedure to open another file mythical procedure to process another file mythical mythical procedure to close current file procedure to gracefully end application

Using If...Then...ElseIf

Occasionally you'll have more than two different branches that you'll want your code to choose from. One of the solutions in this case is to use If.. .Then.. .ElseIf. This variation allows you to choose one of any number of different branches. Listing 3.3 illustrates the use of If.. .Then.. .ElseIf.

Listing 3.3: Using If...Then...ElseIf

Sub TestIfThenElseIf() IfThenElseIf 5, 4 IfThenElseIf 7, 0 IfThenElseIf 13, 4 IfThenElseIf 12, 12 End Sub

Sub IfThenElseIf(n As Integer, y As Integer) If n = 5 Then

Debug.Print "n = 5" ' you could have more statements here ' or you could call another procedure ElseIf n = 6 Then

Debug.Print "n = 6" ' you could have more statements here ' or you could call another procedure ElseIf n = 7 Then

Debug.Print "n = 7" ' you could have more statements here ' or you could call another procedure ElseIf y = 4 Then

' you could have more statements here ' or you could call another procedure


Debug.Print "This is a default action" ' you could have more statements here ' or you could call another procedure End If End Sub

Running TestlfThenElself produces the following output:

This is a default action

This listing draws on some concepts that were covered earlier in the chapter. The main thing to point out is that parameters are used in the declaration of the IfThenElself procedure. Once you declare parameters in the declaration of a procedure, you can use those parameters as you would any other variable in the body of the procedure. Notice in the TestlfThenElself procedure that when you call a procedure that uses parameters, you specify the parameters after the procedure name separated by commas.

The If.. .Then.. .Elself statement in Listing 3.3 highlights the flexibility you are afforded when you use this statement. Specifically, when you are testing the various expressions, nothing prevents you from testing nonrelated variables. For example, the last Elself tests the y variable rather than the n variable. This allows you to construct complicated logic. Be careful not to shoot yourself in the foot with this. You'll find it easy to create such complicated logic using this technique, but it's very difficult to debug or modify it later. In such cases, it's usually a better idea to develop a function specifically to test the expressions.

Another option to using If.. .Then.. .Elself is to consider the Select Case statement, which is covered in the "Choosing Actions with Select Case" section later in the chapter.

Nesting If...Then Statements

You can nest If.. .Then statements to create any branching structure you need or to check for multiple conditions before you execute a statement. It can be easy to lose your place so to speak when you're using nested If statements, so you'll find that it helps to use indenting to clarify which If.. .Then block those statements are associated with. Also, I find it helpful to create the entire skeleton of an If.. .Then.. .Else statement when I first create it and then go back and add the statements that are part of each branch.

A Note on Indenting Code

Indenting your code has the benefit of making your procedures easier to read. The need to indent becomes clear once you start nesting If...Then statements. As with variable naming, how and whether you use indenting is personal preference; however, the style I've used in this book is widely accepted and I'd strongly recommend adopting it.

Choosing an Action Using IIF

An alternative to If.. .Then is the IIF() function. This function behaves just like the IF worksheet function in Excel. The syntax of IIF is as follows:

IIf(expr, truepart, falsepart)

For example:

IIF(1<10, "True. 1 is less than 10", "False. 1 is not less than 10")

would return the text "True. 1 is less than 10".

You'll find IIF useful when you are conducting simple calculations and comparisons. The main limitation of IIF versus If.. .Then is that IIF can't be used to perform branching because you can't execute statements from within IIF().

0 0


  • julia
    What is an example of branching code in VBA?
    7 months ago

Post a comment