Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Long variables work in 64 bit AND 32 bit Excel VBA

I have quite a complex Excel VBA project that runs well on 32-bit systems, I am now trying to make it work for 64-bit systems too. I have resolved all the function declarations, but still get some issues with the Long data type.

Doing some research, I come up with this (from the MSDN pages):

The actual data type that LongPtr resolves to depends on the version of Office that it is running in: LongPtr resolves to Long in 32-bit versions of Office, and LongPtr resolves to LongLong in 64-bit versions of Office.

But does that mean that I can change ALL my Dim statements from

Dim x as Long

to

Dim x as LongPtr

Should I do that everywhere? Or have I got the wrong end of the stick? Are there circumstances where that won't work or this change should be avoided?

like image 725
M. H Avatar asked Jun 07 '14 08:06

M. H


People also ask

Can I have both 32-bit and 64-bit Excel?

The 32-bit and 64-bit versions of Office programs aren't compatible, so you can't install both on the same computer.

How do you define a long integer in VBA?

You can declare and initialize a Long variable by assigning it a decimal literal, a hexadecimal literal, an octal literal, or (starting with Visual Basic 2017) a binary literal. If the integer literal is outside the range of Long (that is, if it is less than Int64. MinValue or greater than Int64.

How do you use long in VBA?

“Long,” as the name says, it should hold the value of something big. “Long” is a numerical data type in VBA Excel. The long data type in Excel VBA can hold the values from 0 to 2, 147, 483, 647 for positive numbers, and for the negative number it can hold from 0 to -2, 147, 483, 648.

Can Excel 32-bit open Excel 64-bit files?

The files created by 32-bit and 64-bit Excel are interchangeable and indistinguishable. Both versions of the program produce the same files. Both open the same files. This forum is a user-to-user support forum.


1 Answers

I agree with @Ken White's answer.
Remark (for some answers):

  • You don't ask to convert your 32-bit project into a 64-bit project (which will not work on 32-bit).
  • You always NEED to declare the variable type (if you are a good programmer)

You can still use the Long data type in Office 64-bit. It will be compatible for running in 32-bit and 64-bit Office.
But sometimes, you don't have the choice, because some object's properties are not the same data type in 32-bit vs. 64-bit. For instance, if you use ADO:

Dim rstTest As ADODB.Recordset 
  • rstTest.RecordCount is Long on 32-bit Office
  • rstTest.RecordCount is LongLong on 64-bit Office

If you want to store rstTest.RecordCount into a lngCount variable, you MUST declare this variable with LongPtr otherwise it won't work on 32-bit AND 64-bit:

Dim lngCount As LongPtr  
lngCount = rstTest.RecordCount
like image 145
Sly Avatar answered Sep 18 '22 19:09

Sly