Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 608
Kyle Avatar asked Apr 06 '12 20:04

Kyle


People also ask

How do you check if a string is not empty?

The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.

How does isEmpty work VBA?

VBA IsEmpty is a logical function that tests whether the selected is empty or not. Since it is a logical function, it will return the results in Boolean values, i.e., TRUE or FALSE. If the selected cell is empty, it will return TRUE, or else it will return FALSE.

Is empty or null?

Sometimes strings can be empty or NULL. The difference is that NULL is used to refer to nothing. However, an empty string is used to point to a unique string with zero length.

What is an empty string in coding?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null . It can be described as the absence of a string instance.


2 Answers

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.

like image 194
Michael Liu Avatar answered Oct 03 '22 18:10

Michael Liu


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
like image 22
Steve Rindsberg Avatar answered Oct 03 '22 19:10

Steve Rindsberg