user1058210
user1058210

Reputation: 1689

VBA - Identifying null string

One of my cells appears to be blank but has a length of 2 characters. I copied the string to this website and it has identified it as a null string.

I have tried using IsNull and IsEmpty, as well as testing to see if it is equivalent to the vbNullString but it is still coming up as False.

How do I identify this string as being Null?

Upvotes: 3

Views: 3720

Answers (2)

Mathieu Guindon
Mathieu Guindon

Reputation: 71157

A string value that "appears to be blank but has a length of 2 characters" is said to be whitespace, not blank, not null, not empty.

Use the Trim function (or its Trim$ stringly-typed little brother) to strip leading/trailing whitespace characters, then test the result against vbNullString (or ""):

If Trim$(value) = vbNullString Then

The Trim function won't strip non-breaking spaces though. You can write a function that does:

Public Function TrimStripNBSP(ByVal value As String) As String
    TrimStripNBSP = Trim$(Replace(value, Chr$(160), Chr$(32)))
End Function

This replaces non-breaking spaces with ASCII 32 (a "normal" space character), then trims it and returns the result.

Now you can use it to test against vbNullString (or ""):

If TrimStripNBSP(value) = vbNullString Then

The IsEmpty function can only be used with a Variant (only returns a meaningful result given a Variant anyway), to determine whether that variant contains a value.

The IsNull function has extremely limited use in Excel-hosted VBA, and shouldn't be needed since nothing is ever going to be Null in an Excel worksheet - especially not a string with a length of 2.

Upvotes: 4

VBasic2008
VBasic2008

Reputation: 54777

Chr(160) Issue

160 is the code number of a Non-Breaking Space.

Let us say the cell is A1.

In any cell write =CODE(A1) and in another (e.g. next to) write =CODE(MID(A1,2,1)).

The results are the code numbers (integers e.g. a and b) of the characters.

Now in VBA you can use:

If Cells(1, 1) = Chr(a) & Chr(b) Then

End If 

or e.g.

If Left(Cells(1, 1), 1) = Chr(160) then

End If

Upvotes: 1

Related Questions