rb982996
asked on
When to use Nested IF?
When would I nest my If's as opposed to making seperate algorithms?
if a = 2 then
msgbox "It equals 2."
else
if a = 3 then
msgbox "It equals 3."
else
if a = 4 then
msgbox "It equals 4."
end if
end if
end if
as opposed to
if a = 2 then
msgbox "it equals 2."
end if
if a = 3 then
msgbox "it equals 3."
end if
if a = 4 then
msgbox "it equals 4."
end if
if a = 2 then
msgbox "It equals 2."
else
if a = 3 then
msgbox "It equals 3."
else
if a = 4 then
msgbox "It equals 4."
end if
end if
end if
as opposed to
if a = 2 then
msgbox "it equals 2."
end if
if a = 3 then
msgbox "it equals 3."
end if
if a = 4 then
msgbox "it equals 4."
end if
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If you use a single If structure or a Select Case clause, only the first 'matching' code will run. If you use several If's, one or many codes can run. Look at this code:
Dim a
a = 3
'SELECT CASE STRUCTURE
Select Case a
Case Is < 10 'This will run
MsgBox "less than 10"
Case Is > 100
MsgBox "more than 100"
Case Int(a) 'But not this one
MsgBox "integer"
Case Else
MsgBox "whatever"
End Select
'IF...ELSEIF...ELSE...ENDI
If a < 10 Then 'This will run
MsgBox "less than 10"
ElseIf a > 100 Then
MsgBox "more than 100"
ElseIf a = Int(a) Then 'But not this one
MsgBox "integer"
Else
MsgBox "Whatever"
End If
'SEVERAL CONSECUTIVE IFS
If a < 10 Then 'This will run
MsgBox "less than 10"
End If
If a > 100 Then
MsgBox "more than 100"
End If
If a = Int(a) Then '...and this also
MsgBox "integer"
End If
I hope I haven't messed this up completely...
Ture Magnusson
Karlstad, Sweden