vba - 测试字符串是否为空

标签 vba ms-word requirements

我是 VBA 的新手,我还没有完全习惯语法,所以如果我的问题听起来很愚蠢,我很抱歉。

我在 Word 2010 中使用 RequisitePro40 和 VBA 7.0。在我的一个模块中,我有以下循环和 If 条件:

Dim rqRequirements As ReqPro40.Requirements
Dim rqRequirement As ReqPro40.Requirement
Const eAttrValueLookup_Label = 4
Dim a As Integer
...

For Each vReqKey In rqRequirements
    Set rqRequirement = rqRequirements(vReqKey)

    If rqRequirement.AttrValue("MyAttreName", eAttrValueLookup_Label).text <> Null Then
        a = 1
    End If

    If rqRequirement.AttrValue("MyAttreName", eAttrValueLookup_Label).text = Null Then
         a = 2
    End If

 Next

在循环的每次迭代中, a = 1 a = 2 被处决!!

基于 This ,等式和不等式运算符是“=”和“<>”。因此,我希望 a = 1 a = 2 执行一个字符串。
我的语法有问题吗?还是与 ReqPro 相关的问题?

我也尝试使用“Is”和“IsNot”运算符,但它们导致编译器错误:类型不匹配

有人可以帮我弄这个吗?

更新:真正的目标是看看是否

rqRequirement.AttrValue("MyAttreName", eAttrValueLookup_Label).text



是否为 Null。我添加了第二个 if 以显示该语句在某种程度上无法按我期望的方式工作的问题。

将“Null”替换为“vbNullString”没有做出任何改变。

我还按照@Slai 的建议尝试了 IsNull 函数。结果几乎相同:
    If IsNull(rqRequirement.AttrValue(att, eAttrValueLookup_Label).text) Then
        a = 3
    End If

    If Not IsNull(rqRequirement.AttrValue(att, eAttrValueLookup_Label).text) Then
        a = 4
    End If

两种说法 a = 3 a = 4 是真实的并被执行。

最佳答案

VBA 不支持测试字符串是否为“Null”。 VBA 不像 .NET 语言或 JavaScript(例如)。基本变量类型都有一个默认值,从声明变量的那一刻起,字符串的长度为零("") - 它没有未实例化的状态。您还可以测试 vbNullString。

如果你测试

Dim s as String
Debug.Print s = Null, s <> Null, s = "", s = "a", IsNull(s), s = vbNullString

返回是
Null  Null  True  False  False  True

因此,如果您尝试测试是否已将任何内容分配给 String 变量,您唯一可以做的事情是:
Debug.Print Len(s), s = "", Len(s) = 0, s = vbNullString

哪个返回
0  True  True True

请注意,这些可能性中最慢的是 s = "" ,尽管这似乎是最容易记住的。

关于vba - 测试字符串是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49067215/

相关文章:

delphi - 如何使用delphi xe5更改word中页码的字体

java - Office Web Apps Word 编辑

c# - 使用open xml和C#将图像插入到word文档中

math - AMN 和数学逻辑符号

php - 如何在 PHP 中为目标建模和跟踪需求

VBA 返回#REF!粘贴值时

Excel VBA 过滤/可见单元格

vba - 如果文件扩展名为 .xls,则 MsgBox

VBA - 复制区域和粘贴区域的大小不同错误?

specifications - 那里有什么好的软件规范/需求工具吗?