View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
keepITcool keepITcool is offline
external usenet poster
 
Posts: 2,253
Default Question about dim statement



Dim x,y as long '=y as long , x as variant.
Dim x,y as string '=y as string, x as variant
Dim x as long,y as long '=correct "combined" syntax.

The errors will start when you assign a variable to another
and 1 is not a variant... Or when you use a function
where either return value or arguments are "typed".


dim s as string, i as integer, l as long, v as variant
'or dim s$, i%, l&, v

v=s 'ok since variant will accept other types
v=i 'ok
v=l 'ok
but
s=v (may give probems depending on the content of v
i=s Will give problems
l=i will give problems...

somae goes for functions/procedure arguments

Function HowLong(s as string) as long
Howlong = len(s)
end function

i=howlong(s) will give a problem as Howlong returns a Long.
l=howlong(v) will also give a problem as Howlong expects a string.

Function HowWide(byval s as string) as long
HowWide=len(s)
end function

l=howwide(v) will now work since the argument s is passed byval
but
i=howwide(v) will NOT work as howwide returns a long.


so.. you could stick to using variants. BUT variant carry a lot of
"fat" and are much slower than using correct types.

also when you use variants for objects you will not have intellisense,
and you may get run time errors that otherwise could be picked up
when compiling.

this stuff is explained in all VB(A) books.
in the first few boring chapters that many people skip cuz they want
to the more exciting stuff....

VBA performance can be very sensitive to correct data typing.
(you may not notice when you run a function 1x.. but you WILL notice
when a function is called 100000 times..)


--
keepITcool
| www.XLsupport.com | keepITcool chello nl | amsterdam


Gregg wrote :

While debugging my code today, I was surprised to find the fix was to
change this dim statement...
Dim lNumber, lValue, lWhatever as Long

to this...
Dim lNumber as Long
Dim lValue as Long
Dim lWhatever as Long

The value would not work correctly unless I separated out the dim
statement. Once I did that, it worked flawlessly and I set it back and
forth to be sure.

I've never encountered that before. I've always been able to place
multiple items in a dim statement. Is Long different? Can someone
enlighten me on this?

Thanks.