To add on to Cindy's excellent answer, I want to point out that while VBA normally has safeguards to coerce the values when assigning to a Boolean
data type, this can be circumvented. Basically, if you write a random value to a memory address that's not yours, then you should expect undefined behavior.
To help demonstrate this, we'll (ab)use LSet
which essentially allow us to copy the value without actually assigning.
Private Type t1
b As Boolean
End Type
Private Type t2
i As Integer
End Type
Private Sub Demo()
Dim i1 As t2
Dim b1 As t1
Dim b As Boolean
i1.i = 1
LSet b1 = i1
b = b1.b
Debug.Print b, b1.b, i1.i
Debug.Print CInt(b), CInt(b1.b), i1.i
End Sub
Note the line b = b1.b
is basically equivalent to what we did in the OP code
X = Selection.Cells(1).FitText
That is, assigning a Boolean
to another Boolean
. However, because I wrote to the b1.b
using LSet
, bypassing VBA runtime checks, it doesn't get coerced. When reading the Boolean
, VBA does implicitly coerce it into either True
or False
, which seems misleading but is correct because any falsy results is one that equals 0
(aka False
), and any truthy results is one that doesn't. Note that the negative for truthy means that both 1
and -1
are truthy.
Had I assigned the 1
to a Boolean
variable directly, VBA would have had coerced it into -1
/True
and thus there'd be no problem. But evidently with FitText
or LSet
, we are basically writing to the memory address in an uncontrolled fashion, so that VBA start to behave strangely with this particular variable since it expects the Boolean
variable to already had its contents coerced but wasn't.
Not
does not work as expected, it does not handle the why behind the behavior here: The Word object model is not behaving according to the rules of VBA. A discussion of that aspect is completely missing in the question linked as a duplicate. – PargetFalse
is 0 (all bits clear), andTrue
is defined asNot False
, which means -1 (all bits set).Causes WinAPI interop issues, too. Any non-zero value is treated asTrue
, so it's only a problem if you start manipulating bits without understanding what;s happening, compounded by the lack of a distinction between bitwise/logical operators. I don't see the merit in re-opening this when the root cause and the solution are fundamentally identical. – KilowattBoolean
, I would have added that as a comment in addition to voting to close. But because there already was a great answer explaining it, I did not have to. The underlying reason is identical, like Cody Gray mentioned, and in addition to that, I see closing as duplicate as a way to link helpful questions together rather than to punish the later asker. – Flivver