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

时间:2012-04-06 20:24:57

标签: vba if-statement string

我的If条件出了什么问题?

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

Not条件似乎无效。即使IfWrkgps_L3都是空字符串,Wrkgps_L4语句中的代码也会被执行。

更新

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

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

无论如何,我仍然很想知道为什么IsEmpty无法处理""的变量?

2 个答案:

答案 0 :(得分:8)

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

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

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

答案 1 :(得分:1)

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

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
相关问题