Kyle
Kyle

Reputation: 947

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

What is wrong with my If condition?

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

The Not condition doesn't seem to work. The code within the If statement gets executed even when both Wrkgps_L3 and Wrkgps_L4 are empty strings.

Update:

Wrkgps_L3 and Wrkgps_L4 are variables that contain results returned from a function. I noticed that IsEmpty(Wrkgps_L3) = False even though Wrkgps_L3 = "". I had to rewrite my code to

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

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

Upvotes: 8

Views: 28270

Answers (2)

Steve Rindsberg
Steve Rindsberg

Reputation: 3528

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

Upvotes: 1

Michael Liu
Michael Liu

Reputation: 55379

In Visual Basic, Empty and "" (an empty string) are two different things. Empty is the uninitialized state of a Variant variable, and IsEmpty tests whether a Variant variable has the Empty value:

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 String variable contains an empty string.

Upvotes: 12

Related Questions