PDA

View Full Version : Two questions: Long and Dim



doctortt
04-05-2011, 02:58 PM
1) Can Dim x as Long handle decimal?


2) Is it necessary to DIM all variables in a VBA program? Can I just declare a few but leave some out?

Paul_Hossler
04-05-2011, 03:06 PM
1) Can Dim x as Long handle decimal?


Yes, but you lose the decimals.


x=123.45


Returns 123.




2) Is it necessary to DIM all variables in a VBA program? Can I just declare a few but leave some out?


No, not necessary but highly recommended, including using Option Explicit at the top of all modules.

OE forces all variables to be Dim-ed, and decreases problems caused my mis-typing

If you don't Dim your variables, VBA makes them all Variant, which also can make debugging more difficult, as well as introducing small delays when VBA has to convert types

My 2 cents ...

Paul

doctortt
04-05-2011, 03:13 PM
Thanks a lot. So what should I do If I want to preserve the decimal? I guess I should use Double, right?

Bob Phillips
04-05-2011, 03:27 PM
Right, as we said yesterday.

doctortt
04-05-2011, 03:28 PM
Got it, hot shot. Thanks

macropod
04-05-2011, 09:44 PM
You could Dim the decimal variable as Single instead of Double. Singles support larger values, Doubles greater precision. It's your choice.

Bob Phillips
04-06-2011, 01:17 AM
It is wasteful to define single (or integer) as it forces two conversions of data, to double (long) when taken by the processing engine, and back to single (integer) when returned.

macropod
04-06-2011, 02:05 AM
Hi James,

If you're working with decimals, why would a conversion to/from double be needed? And how would that be possible for values larger than a double can handle?

Bob Phillips
04-06-2011, 02:19 AM
Because that it what 32/64 bit systems do.