Variables

F

Francis Hookam

Variables

Having only scant knowledge of the use of different types Visual Basic
variables* please direct me to a site where variable types are listed with
an outline of why/where each is used - are they always defined at the
beginning of the Module - etc

Some are obvious (String, Integer - or are they?) and some are not (Long,
Short)

Francis Hookham

* JE McGimpsey¹s recent posting ŒRe:Sum¹ in answer to a question of mine
included:
Dim sYesNo As String
Dim bYesNo As Boolean
Dim dSum As Double
 
J

JE McGimpsey

Francis Hookam said:
Having only scant knowledge of the use of different types Visual Basic
variables* please direct me to a site where variable types are listed with
an outline of why/where each is used - are they always defined at the
beginning of the Module - etc

Some are obvious (String, Integer - or are they?) and some are not (Long,
Short)

For data types, take a look at the "Data Type Summary" and "Using data
types efficiently" topics in VBA Help.

For declaration (defining) of variables, see "Declaring Variables" in
VBA Help.

Module-level and global public variables need to be declared at the top
of a module. However, good coding practice generally frowns on using
global/module-level variables unless absolutely necessary. Instead, most
or all variables should be declared within procedures.

VBA does not require procedure-level variables to be declared, either at
the beginning of a procedure or elsewhere. However, if a variable isn't
declared, it will be of type Variant. This is generally inefficient,
using a larger number of bytes and less optimized code. It also prevents
the compiler from helping to identify errors such as assigning a string
to a numeric variable.

I recommend *always* putting

Option Explicit

at the top of your modules. That requires that variables be declared, so
that situations like this from creating errors in your code:

Dim myVariable As Long
Dim x As Long
'...
'Lots of code here
'...
x = myVriable * 2

If Option Explicit is set, the compiler will flag the x=... line and
tell you that "myVriable" is an undeclared variable. If Option Explicit
is not set, the compiler instead creates a new variant variable and the
result of the multiplication will always be zero. This can be a very
difficult error to catch.

You can set your VBE preferences to always include Option Explicit in a
module. Choose Preferences/Editor and check the "Always require variable
declaration" checkbox.
 

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