VBA:为什么 Not 运算符会停止工作? [英] VBA: Why would the Not operator stop working?

查看:28
本文介绍了VBA:为什么 Not 运算符会停止工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我很困惑.

Sub testChangeBoolean()
  Dim X As Boolean       ' default value is False
  X = True               ' X is now True
  X = Not X              ' X is back to False
End Sub

但我试图在表格单元格中(在 Word 中)切换 .FitText 属性..FitText 以 True 开头.

But I'm trying to toggle the .FitText property in a table cell (in Word). .FitText starts as True.

如果我将它分配给 X:

If I assign it to X:

Sub testChangeBoolean()
  Dim X As Boolean                  ' again, default is False
  X = Selection.Cells(1).FitText    ' does set X to True
  X = Not X                         ' X is still True!
End Sub

我只是不明白我做错了什么.

I just don't understand what I'm doing wrong.

推荐答案

我相信这个解释与较旧的编程语言(WordBasic 和早期的 VBA)如何存储 True 和 False 的整数值有关.在那些日子里,True = -1 和 False = 0.

I believe the explanation has to do with how older programming languages (WordBasic and early VBA) stored the integer values of True and False. In those days, True = -1 and False = 0.

较新的编程语言仍然使用 0 表示 False,但 1 表示 True.

Newer programming languages still use 0 for False, but 1 for True.

Word 的大多数布尔类型属性继续使用 -1 表示 True(例如,Font.Bold),这让使用新语言的 Interop 的程序员感到困惑和沮丧.因此,在某些时候,Microsoft 的一些开发人员决定使用新方法并将整数值 1 分配给 True 以实现某些新功能.如FitText.

The majority of Word's Boolean type properties continue to use -1 for True (Font.Bold, for example), which has been cause for confusion and frustration for programmers working with the Interop in newer languages. So, at some point, some developers at Microsoft decided to use the new way and assigned the integer value of 1 to True for some new functionality. Such as FitText.

考虑以下代码示例,其中 X 的类型为 Boolean,而 y 的类型为 Integer:

Considering the following code sample, where X is of type Boolean and y of type Integer:

  • 如果 FitText 为 True,则整数值为 1
  • 如果反转值,使用 Not 表明布尔值保持真",因为它的整数值不是 0,而是 -2
  • 将整数值直接设置为 True 会得到 -1
  • If FitText is True, the integer value is 1
  • If reversing the values, using Not shows that the Boolean remains "True" because its integer value is not 0, it's -2
  • Setting the integer value directly to True gives -1

这确实令人困惑,但确实解释了为什么 Not 没有给出预期的结果.

This is confusing, indeed, but does explain why Not is not giving the expected result.

Sub testChangeBoolean()
  Dim X As Boolean                  ' again, default is False
  Dim Y As Integer
  X = Selection.Cells(1).FitText    ' does set X to True
  Y = Selection.Cells(1).FitText
  Debug.Print X, Y                  ' result: True    1
  X = Not X                         ' X is still True!
  Y = Not Y
  Debug.Print X, Y                  ' result: True   -2
  X = False
  Y = True
  Debug.Print X, Y                  ' result: False  -1
End Sub

这篇关于VBA:为什么 Not 运算符会停止工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆