vba 为什么 If Not IsEmpty 不过滤掉空字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10048855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 12:54:40  来源:igfitidea点击:

Why doesn't If Not IsEmpty filter out empty strings?

vbaif-statementstring

提问by Kyle

What is wrong with my Ifcondition?

我的If病情有什么问题?

If Not IsEmpty(Wrkgps_L3) And Not IsEmpty(Wrkgps_L4) Then
    Wrkgps_L3L4 = Wrkgps_L3 & "," & Wrkgps_L4
End If

The Notcondition doesn't seem to work. The code within the Ifstatement gets executed even when both Wrkgps_L3and Wrkgps_L4are empty strings.

Not条件似乎不起作用。If即使Wrkgps_L3Wrkgps_L4都是空字符串,语句中的代码也会被执行。

Update:

更新:

Wrkgps_L3and Wrkgps_L4are variables that contain results returned from a function. I noticed that IsEmpty(Wrkgps_L3) = Falseeven though Wrkgps_L3 = "". I had to rewrite my code to

Wrkgps_L3Wrkgps_L4是包含从函数返回的结果的变量。我注意到IsEmpty(Wrkgps_L3) = False即使Wrkgps_L3 = "". 我不得不重写我的代码

If (Wrkgps_L3 <> "") And (Wrkgps_L4 <> "") Then

In any case, I am still intrigued to know why IsEmptydoesn't work on variables with ""?

无论如何,我仍然很想知道为什么IsEmpty不能使用""?

回答by Michael Liu

In Visual Basic, Emptyand ""(an empty string) are two different things. Emptyis the uninitialized state of a Variantvariable, and IsEmptytests whether a Variantvariable has the Emptyvalue:

在 Visual Basic 中,Empty""(空字符串)是两个不同的东西。EmptyVariant变量的未初始化状态,并IsEmpty测试Variant变量是否具有Empty值:

Dim x As Variant
If IsEmpty(x) Then
    Debug.Print "x is empty"
End If

As you've observed, you must compare against ""when checking whether a Stringvariable contains an empty string.

正如您所观察到的,您必须""在检查String变量是否包含空字符串时进行比较。

回答by Steve Rindsberg

If the variables are strings, you could also:

如果变量是字符串,您还可以:

If Len(Wrkgps_L3) + Len(Wrkgps_L4) = 0 Then
   ' They're both empty string variables
Else
   ' One or the other contains at least one character
End If