gpt4 book ai didi

vba - 测试字符串是否为空

转载 作者:行者123 更新时间:2023-12-04 17:30:38 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com