VBA power operator (^) not working as expected in 64-bit VBA [duplicate]

你离开我真会死。 提交于 2020-03-02 10:06:32

问题


I feel foolish for asking and I'm sure there's a simple answer. I'm trying to get a power for a number as follows:

Sub test()

Dim number As Long

number = 2^8 ' Expect to get 256 here

End Sub

This produces an error: 'Expected: list separator or )'.

I'm surprised this doesn't work. I'm aware that there's an Excel defined power function. But is the ^ operator not supported in VBA - it is in VB6?

FURTHER INFO

If I do the same in the Immediate window, I get the following strangeness (no error):

?2^8
 2  8

It looks like just spaces between the 2 and the 8.

IT WORKS?

So I was messing about with various combinations of symbols and found that in the Immediate window:

?2^^8
 256

What the...? Anyone know why this might be?

MORE EXPERIMENTS

I'm guessing my installation of Excel must be broken (although absolutely everything else works fine). Some further things the Immediate window:

If I insert a space before ^:

?2 ^3
 8

?2!^3
 8

?2"^3
 2 ^3

?2£^3
 2  0  3

?2%^3
 8

?2@^3
 8

?2#^3
 8

回答1:


Confirmed: Also happens in MS Word 2010, 2013, 2016 all 64 bit Office*1

*1 I suspect this applies to most of, if not all, the 64 bit office applications

This seems to be an issue with the 64 bit version of MS Office. In the 32 bit version the caret ^ is used for the power operator, however in the 64 bit operator it is also used for variables of type LongLong (docs.microsoft.com/.../vba/.../longlong-data-type).

In 64 bit VBA, when using Debug.Print*2 the IDE auto corrects 2^2 to 2^; 2 but 2 ^2 is auto-corrected to 2 ^ 2; making the code compile-able.

By way of a solution, this is just one of those annoying things that users of 64bit VBA 'just need to know'.


Edit: Microsoft confirmed issue https://support.microsoft.com/en-gb/help/2454019/the-64-bit-office-2010-vba-compiler-shows-an-error-when-it-encounters

*2 I've also come to learn that the VBA behavior is different when using debug.Print than assigning a variable (thanks to @ErikvonAsmuth)




回答2:


You can use the powerfunction. For example

Sub Test()
Dim number As Long
number = Application.WorksheetFunction.power(2, 8)
End Sub

But the ^ operator must have been working too .



来源:https://stackoverflow.com/questions/51264287/vba-power-operator-not-working-as-expected-in-64-bit-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!