VBA takes wrong branch at If-statement - severe compiler bug?
This bug is not present on 32-bit, but it seems to be present in 64-bit VBA-capable applications (I've tried Excel, Word, and AutoCAD).
Since the question already covers what happens if the Object does not get terminated or if there is no Class_Terminate
event, the following examples all use an Object that will surely go out of scope and we also assume there is a Class_Terminate
that gets called:
Option Explicit#If Win64 ThenSub Bug() ' We don't really need a Clone method to reproduce the bug If Falsee(New cClass) Then Debug.Print "This does print, although it shouldn't!" End If ' If we add a logical operator and a second method call then the bug disappears: If Falsee(New cClass) Or Falsee(New cClass) Then Debug.Print "This doesn't print, as it shouldn't." End If ' It could be any other method. The order of the methods also doesn't matter If Falsee(New cClass) Or Sin(0) Then Debug.Print "This doesn't print, as it shouldn't." End If ' The above workaround does not work if we simply use a boolean value after the method call If Falsee(New cClass) Or False Then Debug.Print "This does print, although it shouldn't!" End If ' But it does work if we add the boolean before the method call: If False Or Falsee(New cClass) Then Debug.Print "This doesn't print, as it shouldn't." End If If True And Falsee(New cClass) Then Debug.Print "This doesn't print, as it shouldn't." End IfEnd SubFunction Falsee(oClass As cClass) As Boolean Falsee = FalseEnd Function#End If
It is indeed a bug of the 64-bit version of VBA7. Here's a smaller example:
SomeClass.cls:
Private Sub Class_Terminate()End Sub
Main.bas:
Function ReturnFalse(o As Object) As Boolean ReturnFalse = FalseEnd FunctionSub test() Debug.Print ReturnFalse(New SomeClass) If ReturnFalse(New SomeClass) Then Debug.Print "True" Else Debug.Print "False" End If End Sub
This prints
FalseFalse
on 32-Bit VBA and
FalseTrue
on 64-Bit VBA
I could find a report on this error in an almost three year old uservoice post (https://excel.uservoice.com/forums/304921-excel-for-windows-desktop-application/suggestions/35735881-fix-inlined-member-calls-on-user-objects-on-64-bi), but there hasn't been a reaction since then. Also, there is apparently no user accessible "real" way to report VBA bugs to Microsoft. This is all very frustrating, because we have a few VBA projects that direly need porting to 64-bit because of their memory requirements.