8

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 ""?

3
  • 1
    Is it possible you're confusing Null and Empty? e.g. Not IsEmpty(null) returns true Commented Apr 6, 2012 at 20:28
  • I think you need to apply brackets around the conditions like this If ((Not IsEmpty(Wrkgps_L3)) And (Not IsEmpty(Wrkgps_L4))) Commented Apr 6, 2012 at 20:37
  • I'd say you need more parenthesis :)) Commented Apr 6, 2012 at 20:54

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The only thing to add is that If x = Empty returns True in case x contains an empty string. But don't do this, it's an implicit conversion sugar which is better to avoid unless you know for sure what is happening under the hood.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.