Dimension problem

  • Thread starter Thread starter APH
  • Start date Start date
A

APH

Hi - can someone explain the following please?

if I set up:

dim i , j, k, As Integer

i = 3.7
j = 3.7
k = 3.7

MsgBox i
MsgBox j
MsgBox k

Do the first two MsgBox show 3.7 and only the third as 4.00

In my basic understanding I am assuming that VB will only dim the variable
immediately to the left of As Integer and for the others it waits to set
their type until it comes across them. If this is right, is it bad
programming to declare similar cariable types on a single linbe

thanks

Alex
 
Alex,

VB is doing exactly what it should. When you declare variables
with the syntax

dim i , j, k, As Integer

only the variable k is an integer. I and j are Variants. Your
syntax is the same as

Dim i As Variant, j As Variant, k As Integer

When you assign a value of 3.7 to i and j, VBA gives the variant
a subtype of Double. Whether you should declare more than one
variable on a single line of code is a matter of personal
programming style. I don't like it, but others do. Go with your
own style.


--
Cordially,
Chip Pearson
Microsoft MVP - Excel
Pearson Software Consulting, LLC
www.cpearson.com
 
dim i , j, k, As Integer
.....would raise an error !!
Otherwise I'd agree with Chip, plus I'd add two further
comments: One would be that more descriptive variable
names make code much clearer to debug, and second, that
adding
Option Explicit
at the top of the module is a MUST...thuis can be set
automatically under the IDE Tools/Options Editor tab and
checking the 'Require Variable Declaration' box.

best regarsd

Patrick Molloy
Microsoft Excel MVP
 
Thanks Chip - I have learnt something today.....
I tend to always declare on a separate line, but this arose as I was at a
training sessions yesterday, when the trainer ran in to the problem in his
own code....

It was just for my own personal knowledge.. thanks again

Alex
 
Thanks Patrick -
Please see my response to Chip - and I agree, I tend to use far more
descriptive variable anmes - I hate looking at code that uses just a single
letter.

I am assumiong that Option Explicit, forces you to delcare variable before
you use them.

Alex
 
dim i , j, k, As Integer
....would raise an error !!

Odds are Chip missed the original typo.
. . . One would be that more descriptive variable
names make code much clearer to debug, . . .

Begging the question how descriptive array indices need to be. Constants and
long lived variables should have descriptive names. Short lived variables
usually don't need them.
 
Back
Top