ElseIf versus Nested If

  • Thread starter Thread starter DCPan
  • Start date Start date
D

DCPan

Hi,

I was wondering, is there any real reason to use ElseIf other than that it
saves you from having to write End If twice?

Thanks!
 
DCPan said:
I was wondering, is there any real reason to use ElseIf other than that it
saves you from having to write End If twice?


More than a couple levels of nested Ifs can become rather
difficult to keep track of. ElseIf avoids the nesting as
well as the additional End If statements.

You may also want to look at the Select Case statement.
 
There is certainly quite a different insignificant behavior between the two

eg:

first example:

dim intNum as interger

intNum = 200

if intNum > 5 then
msgbox "the number is greater then 5"
end if

if intNum > 15 then
msgbox "the number is greater then 15"
end if

-------------

In the above case...you ALWAYS see two messages. If you used elseif...such
as:

if intNum > 5 then
msgbox "the number is greater then 5"
else if intNum > 15 then
msgbox "the number is greater then 15"
end if
 
Hi Albert,

I was more thinking along the lines of:

Sub test1()

Dim intNum As Integer
intNum = 200

If intNum > 15 Then
MsgBox "the number is greater then 15"
ElseIf intNum > 5 Then
MsgBox "the number is greater then 5"
End If

End Sub

Sub test2()

Dim intNum As Integer
intNum = 200

If intNum > 15 Then
MsgBox "the number is greater then 15"
Else
If intNum > 5 Then
MsgBox "the number is greater then 5"
End If
End If

End Sub
 
Neither approach is superior. However, ElseIf is far more elegant and less
bulky. Its a saving grace. Having the option to use it over nested Ifs, I
cant think of a single reason why I wouldnt.
 
The If ...Elseif....ElseIf...Else..End If structure has the advantage of
being easier to read and the minor advantage of skipping all succeeding
tests once the first test evaluates as true. With modern computers that
advantage may be minuscule unless one or more of the tests involves another
function that takes time to perform. I do have some functions that take
several seconds to execute and return true or false.





--
John Spencer
Access MVP 2002-2005, 2007-2008
Center for Health Program Development and Management
University of Maryland Baltimore County
..
 
Back
Top