Problem
You need to make some logical tests and branch your code accordingly.
Solution
Use If/Then statements as illustrated in Example 2-11.
Example 2-11. If statements
If (time = 32000) then ' Statements go here End If If (MyCondition = True) Then ' Statements Else ' More statements End If If (count < 10) Then ' Statements ElseIf (count < 20) Then ' Statements ElseIf (count < 30) Then ' Statements End If |
If statements start with the If keyword followed by a logical expression, which is followed by the Then keyword. If the logical expression is true, the code between the If statement and the End If statement gets executed. You can also use the Else keyword to define a block of code to execute if the logical expression is false. Further, you can use the ElseIf keyword to test other conditions in a series of If-Then-ElseIf-Then statements.
You'll notice I enclose the logical expressions being evaluated in parentheses. VBA does not require this; I do so only because it is more readable to me. (It's also kind of a habit I picked up from programming in C.)
See Also
Sometimes you may encounter situations where you have a lot of conditions to test and you find yourself with long, strung out If-Then-ElseIf-ElseIf-Then statements. In these situations, you may find VBA's Select Case statement more appropriate. Select Case statements are handy when you're testing for different values of a numerical expression or text. See the VBA help topic "Select Case Statement" for more information.
Using Excel
Getting Acquainted with Visual Basic for Applications
Collecting and Cleaning Up Data
Charting
Statistical Analysis
Time Series Analysis
Mathematical Functions
Curve Fitting and Regression
Solving Equations
Numerical Integration and Differentiation
Solving Ordinary Differential Equations
Solving Partial Differential Equations
Performing Optimization Analyses in Excel
Introduction to Financial Calculations
Index