Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA - Identifying null string

Tags:

null

excel

vba

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?

like image 960
user1058210 Avatar asked Dec 03 '25 15:12

user1058210


1 Answers

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.

like image 87
Mathieu Guindon Avatar answered Dec 05 '25 14:12

Mathieu Guindon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!