Excel 2010 VBA - Should I initialize variables?

I'm an old school COBOL programmer and I'm used to initializing variables before using them.  Should I do that when programming in VBA?
brothertruffle880Asked:
Who is Participating?
 
Martin LissOlder than dirtCommented:
There is no need to initialize variables that are defined in a Sub or a Function. VBA does it for you.
0
 
Martin LissOlder than dirtCommented:
BTW I did COBOL > 40 years ago.

I should also amend my first post to say that any version of VB does the same.
0
 
NorieVBA ExpertCommented:
It depends what type of variables they are.

Some like object variable you will need to initialize, others you won't but it wouldn't do any harm if you did.

Actually, some variables are kind of initialized anyway.

For example if you declare a variable as Integer it will have the initial value 0.

Declare as a string and a variable will have the initial value of "", an empty string.
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
Martin LissOlder than dirtCommented:
It depends what type of variables they are.

Some like object variable you will need to initialize, others you won't but it wouldn't do any harm if you did.

Actually, some variables are kind of initialized anyway.
Variables are variables and objects are objects. With objects you create new ones which is different than initialization. What do you mean by 'kind of"??
0
 
NorieVBA ExpertCommented:
Martin

Object variable - a variable that refers to an object.

By 'kind of' I mean that they aren't given a value, which might not be regarded as initalisation exactly.
0
 
Martin LissOlder than dirtCommented:
Okay I'm sure that's the official definition of an object but you don't say MyObject = 0 but rather Set MyObject = Whatever-objcet-type-it-is.

VB always gives a variable an initial value even if its 0 or "".
0
 
NorieVBA ExpertCommented:
Sorry I'm a bit lost.

I'm not suggesting using something like MyObject = 0.

I know you initialize object variables by setting them to reference and object.
0
 
Martin LissOlder than dirtCommented:
@brothertruffle880: Let me apologize for imnorie's and my discussion of objects which probably doesn't interest you.

The answer to your question is in my first post with some additional info in imnorie's first post describing what the variables are initialize to.
0
 
Martin LissOlder than dirtCommented:
Glad I was able to help.

Marty - MVP 2009 to 2012
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.