I want to execute one out of 5 formulas depending on whether a switch
variable takes the value 1, 2, 3, 4 or 5. Most programming languages have a
"switch p, case 1 F1, 2 F2, etcetera construct. Does that also exist in
Excel? I am using office 2003.
There is Select Case statement, kind of like so:
Public Sub switchDemo()
Dim p As Integer
p = Int(Rnd() * 10)
Debug.Print "P = " & p
Select Case p
Case 0:
Debug.Print "Failure!"
Case 1, 2, 3:
Debug.Print "Between 1 and 3"
Case 4, 5, 6:
Debug.Print "Between 4 and 6"
Case Else:
Debug.Print "Too high"
End Select
End Sub
However, I am under the impression that this is less efficient than a
multiple If-Then-Else structure, so unless you have many cases and
resulting readability issues, I would probably go with this:
Public Sub multiIf()
Dim p As Integer
p = Int(Rnd() * 10)
Debug.Print "P = " & p
If (p) Then
If (p < 4) Then
Debug.Print "Between 1 and 3"
ElseIf (p < 7) Then
Debug.Print "Between 4 and 6"
Else
Debug.Print "Too high"
End If
Else
Debug.Print "Failure!"
End If
End Sub