Testing if a string is null

dieKoderin picture dieKoderin · Mar 2, 2018 · Viewed 19.8k times · Source

I am pretty new in VBA and I have not yet got used to the syntax completely, so I'm sorry if my question sounds stupid.

I am working with RequisitePro40 and VBA 7.0 in Word 2010. In one of my modules I have the following loop and If conditions:

Dim rqRequirements As ReqPro40.Requirements
Dim rqRequirement As ReqPro40.Requirement
Const eAttrValueLookup_Label = 4
Dim a As Integer
...

For Each vReqKey In rqRequirements
    Set rqRequirement = rqRequirements(vReqKey)

    If rqRequirement.AttrValue("MyAttreName", eAttrValueLookup_Label).text <> Null Then
        a = 1
    End If

    If rqRequirement.AttrValue("MyAttreName", eAttrValueLookup_Label).text = Null Then
         a = 2
    End If

 Next

In each iteration of the loop, both a = 1 and a = 2 are executed!!

Based on This, the equality and inequality operators are "=" and "<>". Therefore I would expect that either a = 1 or a = 2 execute for a string. Is there something wrong with my syntax? Or is it a ReqPro related Problem?

I also tried using "Is" and "IsNot" operators but they result in Compiler error: Type mismatch

Can Someone help me with this?

Update: The actual goal is to see if the

rqRequirement.AttrValue("MyAttreName", eAttrValueLookup_Label).text

is Null or not. I added the second if to show the problem that the statement is somehow not working the way I expect it to work.

Replacing "Null" to "vbNullString" did not make any changes.

I also tried the IsNull function as @Slai suggested. the result is pretty much the same:

    If IsNull(rqRequirement.AttrValue(att, eAttrValueLookup_Label).text) Then
        a = 3
    End If

    If Not IsNull(rqRequirement.AttrValue(att, eAttrValueLookup_Label).text) Then
        a = 4
    End If

Both statements a = 3 and a = 4 are true and executed.

Answer

Cindy Meister picture Cindy Meister · Mar 2, 2018

VBA doesn't support testing whether a string is "Null". VBA isn't like a .NET language or JavaScript (for example). The basic variable types all have a default value, a String is of zero length ("") from the moment the variable is declared - it has no uninstantiated state. You can also test for vbNullString.

If you test

Dim s as String
Debug.Print s = Null, s <> Null, s = "", s = "a", IsNull(s), s = vbNullString

The return is

Null  Null  True  False  False  True

So if you're trying to test whether anything has been assigned to a String variable the only things you can do are:

Debug.Print Len(s), s = "", Len(s) = 0, s = vbNullString

Which returns

0  True  True True

Note that the slowest of these possibilities is s = "", even though it seems the simplest to remember.