Conditional Statements
One of the fundamental elements of programming is making decisions based on inputs. Visual Basic provides the If statement for making either/or decisions and the Select statement for making multiple-choice decisions. These two statements form the core of any logic your program uses to adjust to different conditions, and for that reason they are called conditional
statements
.
The If statement has several different forms:
A very simple one-line form:
If IsArray(Selection) Then MsgBox "Multiple cells selected."
A block form that can contain multiple lines and alternative actions:
Dim str As String If IsArray(Selection) Then str = "Grand total: " & _ WorksheetFunction.Sum(Selection) Else str = "Please select more than one cell" End If MsgBox strA block form with multiple conditions and alternate actions:
If IsArray(Selection) Then str = "Grand total: " & _ WorksheetFunction.Sum(Selection) ElseIf TypeName(ActiveSheet) = "Worksheet" Then str = "Worksheet total: " & _ WorksheetFunction.Sum(ActiveSheet.UsedRange) Else str = "Please select a worksheet" End If MsgBox str
You can have multiple ElseIf statements within an If block as shown by the following general form:
IfconditionThen ' Do something [ElseIfconditionThen ' Do something else] [ElseIfconditionThen ' Can repeat ElseIf] [Else ' Do something else] End If
For more complex logic, you can include If statements within an enclosing If statement, or you can use the Select Case statement. The following ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access