# 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

###### Who is Participating?

Commented:
If your code changed the value of 'a' in the first branch then the subsequent branches could be called.

eg.

if a = 2 then
msgbox "It equals 2."
...
a = 3
endif

if a = 3 then
msgbox "It equals 3."
end if

This should be considered.  You may or may not want that to happen.  Speedwise there is not much between a case and a well structured set of if's.

However the great saving comes in ease of reading and maintainability, most people (me included) would prefer to see a select case, its much neater and clearer.
0

Commented:
rb982996,

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...ENDIF STRUCTURE

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