View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
Peter T Peter T is offline
external usenet poster
 
Posts: 5,600
Default VBA code optimization - why using long instead of integer?

AFAIK the compiler does not convert a number from one data type to another.
However an Integer gets converted to a long at the moment it is used, in
effect an extra process.

In practise I don't suppose you'd notice the difference between calculating
with Integers vs Longs (assuming numbers within 32k). However it does not
serve any useful purpose to declare Integer variables.

A common catch is when an Integer variable is used to refer to a cell row,
then wonder why the code fails when it tries to refer to any row over 32767

Regards,
Peter T



"Thao" wrote in message
...
But if the compiler converts integer variable to long, it means that
declaration variables as integer or long is not important anymore since at
run-time, all of them are long.
Eg: 2 same VBA codes, one is using Integer, the other is using Long. At
run-time,using the same computer will these two codes finish running at
the
same time?

Why do they still recommend that we should use Long when writing the VBA
code instead of Long since both will be Long after compiling?

Thanks and best regards,
Thao Vo

"Peter T" wrote:

Short answer, in 32-bit systems 2 byte integers are converted to 4 byte
Longs. There really is no other way so that respective bits correctly
line
up for any form of processing. Consider the following

MsgBox Hex(-1) = Hex(65535) ' = True

Obviously -1 does not equal 65535 yet the computer is returning the
correct
answer, namely
"FFFF" = "FFFF"

However had we coerced the -1 to a long first we would have got the right
answer (the 65535 being greater than 32k is automatically a long)

MsgBox Hex(-1&) = Hex(65535) ' = False
"FFFFFFFF" = "FFFF"

Generally there is no point in VBA to declare "As Integer" in modern
systems, except perhaps for some legacy API's that expect to receive an
Integer.

Regards,
Peter T



"Thao" wrote in message
...
Can anyone explain to me that why VBA converts all integer values to
long
to
make the program run faster? Mean that Integer is meaningless?

"VBA converts all integer values to type Long, even if they are
declared
as
type Integer. In fact, Long variables might be slightly faster because
VBA
does not have to convert them."