Explicit Variable Declaration vs Non-Explicit Variable Declaration

  • Thread starter Navy Seal via AccessMonster.com
  • Start date
N

Navy Seal via AccessMonster.com

Hi

Can someone please epxlain to me the pros and cons of

Explicit Variable Declaration (ex: Dim myString as String)

vs

Non-Explicit Variable Declaration (No declaration, just value assignemnt:
myString = "Hello")

ty
 
R

Roger Carlson

If you don't define a variable, it will by default use the Variant datatype,
with is the largest VB datatype. Variants can hold any kind of data, so if
code depends on a certain type (say, if you are doing math on a variable so
you need a numeric), then your code will break if the wrong datatype is
entered (ie text in a numeric).

The biggest thing in my opinion is the automatic code checking that Option
Explicit give to your code. Suppose you had the following code:

Sub test()
MyString = "Hello"
Debug.Print MuString
End Sub

As you can see, I mis-spelled MyString in the Debug.Print line. With Option
Explicit on, the code will tell you there's an error at compile time.
Without Option Explicit, the code will merrily execute without any
indication that there's an error, but it still won't print anything. Now,
not printing to the immediate window is no big deal, but suppose the value
of MyString is vitally important to some critical code later in the sub?
Right, you would get the wrong answer and it might take you a long time to
figure out why.

Explicit declarations are so easy and solve so many problems, there's no
reason not to use them.

--
--Roger Carlson
MS Access MVP
Access Database Samples: www.rogersaccesslibrary.com
Want answers to your Access questions in your Email?
Free subscription:
http://peach.ease.lsoft.com/scripts/wa.exe?SUBED1=ACCESS-L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top