Results 1 to 28 of 28

Thread: [RESOLVED] vbNullString vs ""

  1. #1

    Thread Starter
    PowerPoster isnoend07's Avatar
    Join Date
    Feb 2007
    Posts
    3,237

    Resolved [RESOLVED] vbNullString vs ""

    Dim sReturn as string
    sReturn = Inputbox("Enter your name")
    If sReturn <> "" Then
    or
    If sReturn <> vbNullString Then
    Have seen people using vbNullString and have never understood why?
    Is their a reason ?
    Waiting for a full featured smart phone with out marrying a provider
    Go Android
    Go raiders

  2. #2
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: vbNullString vs ""

    The reason depends on the need.

    The string "" takes memory. It contains 4-6 bytes of memory. StrPtr("") will not return zero. 4 of the bytes are the length: 0. Not positive if 2 bytes are actually used to store the string which would be chr$(0) & chr$(0) if stored.

    vbNullString requires no memory. StrPtr(vbNullString)=0

    Some APIs may require vbNullString vs "". While others will fail if you pass vbNullString vs "".


    Edited: Though if you typed: MsgBox CBool("" = vbNullString), you'd get True. That is they both are zero-length strings. But they are different.
    If you wanted to know, for example, whether a user pressed OK or Cancel from an InputBox that had no text entered into it, test the return value with StrPtr. If the value is zero, user hit cancel (vbNullString), if it is non-zero, user hit Ok ("")
    Last edited by LaVolpe; Jan 27th, 2009 at 06:44 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  3. #3
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: vbNullString vs ""

    vbNullString is also marginally faster as it always exists, whereas an empty string needs to be created. It is extremely rare for the speed difference to be noticeable tho.

  4. #4

    Thread Starter
    PowerPoster isnoend07's Avatar
    Join Date
    Feb 2007
    Posts
    3,237

    Re: vbNullString vs ""

    So i guess they both do the same thing check for nothing entered
    Waiting for a full featured smart phone with out marrying a provider
    Go Android
    Go raiders

  5. #5
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431

    Re: vbNullString vs ""

    That's actually not true for either case. In other words if you do not enter anything in the InputBox neither If will be True. They only work if you enter 1 or more blanks. However the following always works and has the advantage of also checking for Cancel being clicked.

    Code:
    If LenB(sReturn) = 0 Then
        MsgBox "lenb = 0"
    End If

  6. #6
    Cumbrian Milk's Avatar
    Join Date
    Jan 2007
    Location
    0xDEADBEEF
    Posts
    2,448

    Re: vbNullString vs ""

    An alternative is...
    Code:
    If Lenb(String) Then 'String is neither zero length nor none existent
    Edit: oops did not see you there martin which means an embarrassing 7 minutes plus to post one line, sheesh
    Last edited by Milk; Jan 28th, 2009 at 06:22 AM.

  7. #7
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: vbNullString vs ""

    Quote Originally Posted by isnoend07
    So i guess they both do the same thing check for nothing entered
    Yes and no...
    Code:
    Private Sub Command1_Click()
        Dim s As String
        s = InputBox("Just press OK")
        Debug.Print s = "", s = vbNullString
        Debug.Print StrPtr(s); " when OK pressed"
    
        s = InputBox("Enter anything or nothing and press Cancel")
        Debug.Print s = "", s = vbNullString
        Debug.Print StrPtr(s); " when Cancel pressed"
    End Sub
    Both will tell you whether the the InputBox return value is "blank" or not. But checking with StrPtr will tell you whether Cancel was clicked or not.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  8. #8
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431

    Re: vbNullString vs ""

    I disagree. When I press OK without entering anything with this code only the last msgbox shows up.

    Code:
    Dim sReturn As String
    sReturn = InputBox("Enter your name")
    If sReturn <> "" Then
     MsgBox "blank"
    End If
    If sReturn <> vbNullString Then
        MsgBox "null"
    End If
    If LenB(sReturn) = 0 Then
        MsgBox "lenb = 0"
    End If

  9. #9

    Thread Starter
    PowerPoster isnoend07's Avatar
    Join Date
    Feb 2007
    Posts
    3,237

    Re: vbNullString vs ""

    Quote Originally Posted by Milk
    An alternative is...
    Code:
    If Lenb(String) Then 'String is neither zero length nor none existent
    I think there is a difference in thinking here, kind of mind bending
    I am checking for is empty and that code checks for not empty
    It works like this:
    If Not LenB(FromEmailAddress) Then
    MsgBox "No mail sent"
    End If
    Exit Sub
    Waiting for a full featured smart phone with out marrying a provider
    Go Android
    Go raiders

  10. #10
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: vbNullString vs ""

    Quote Originally Posted by MartinLiss
    I disagree. When I press OK without entering anything with this code only the last msgbox shows up.

    Code:
    Dim sReturn As String
    sReturn = InputBox("Enter your name")
    If sReturn <> "" Then
     MsgBox "blank"
    End If
    If sReturn <> vbNullString Then
        MsgBox "null"
    End If
    If LenB(sReturn) = 0 Then
        MsgBox "lenb = 0"
    End If
    To test if it is "blank", test for = not <>
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  11. #11
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: vbNullString vs ""

    Quote Originally Posted by isnoend07
    I think there is a difference in thinking here, kind of mind bending
    I am checking for is empty and that code checks for not empty
    It works like this:
    If Not LenB(FromEmailAddress) Then
    MsgBox "No mail sent"
    End If
    Exit Sub
    There are several ways to do the comparison
    If Not LenB(FromEmailAddress)
    If LenB(FromEmailAddress)=0
    If FromEmailAddress = ""
    If FromEmailAddress = vbNullString
    If Len(FromEmailAddress)=0
    ... and we can probably find some other combinations/tests too
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  12. #12

    Thread Starter
    PowerPoster isnoend07's Avatar
    Join Date
    Feb 2007
    Posts
    3,237

    Re: vbNullString vs ""

    Didn't realize so much action for a little question. Thanks guys I have roof estimating software that contains hundred of
    With Grid
    If .textmatrix(2,3) <>"" or .textmatrix(3,3) <> "" then
    .textmatrix(1,3) = val(.textmatrix(2,3)) / val(.textmatrix(3,3)) and textboxs all over with calculations. Of course the cells and boxes can only except numbers
    1 minus sign in the left most position. 1 decimal point. This thread has made me realize i did not account fot the spacebar being used
    Waiting for a full featured smart phone with out marrying a provider
    Go Android
    Go raiders

  13. #13
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: vbNullString vs ""

    You will have to check each value before performing calculation... there's also divide by zero to consider.

    If data is coming from the database, you might be better of doing the calculation via sql and repopulating relevant column in grid/gui.

  14. #14
    Junior Member
    Join Date
    Jan 2009
    Posts
    16

    Re: vbNullString vs ""

    I like to use the following especially in textboxes:

    Code:
    If LEN(TRIM(FromEmailAddress)) = 0 Then . . . .
    This will prevent the space from being saved

  15. #15

    Thread Starter
    PowerPoster isnoend07's Avatar
    Join Date
    Feb 2007
    Posts
    3,237

    Re: vbNullString vs ""

    Quote Originally Posted by leinad31
    You will have to check each value before performing calculation... there's also divide by zero to consider.

    If data is coming from the database, you might be better of doing the calculation via sql and repopulating relevant column in grid/gui.
    It's been so long since i wrote the code i went and looked and have a lot of
    If val(.textmatrix(2,3)) <> 0 or val(.textmatrix(3,3)) <> 0 then
    if the cell is empty it will return 0
    Waiting for a full featured smart phone with out marrying a provider
    Go Android
    Go raiders

  16. #16
    PowerPoster CDRIVE's Avatar
    Join Date
    Jul 2007
    Posts
    2,620

    Re: vbNullString vs ""

    isnoend07, I've often wondered about this topic but didn't have the guts to ask. I'm sure glad that you did. The replies far exceeded what I ever would have imagined!
    <--- Did someone help you? Please rate their post. The little green squares make us feel really smart!
    If topic has been resolved, please pull down the Thread Tools & mark it Resolved.


    Is VB consuming your life, and is that a bad thing??

  17. #17
    Fanatic Member schoolbusdriver's Avatar
    Join Date
    Jan 2006
    Location
    O'er yonder
    Posts
    1,020

    Re: vbNullString vs ""

    You can also use 'IsNull' where appropriate. i.e. to check a variant string array:

    vb Code:
    1. If IsNull(varRet) Then
    2.    txtMsgs.Text = "Meh!"
    3. Else
    4.    For Each strRet In varRet
    5.       txtMsgs.Text = txtMsgs.Text & vbCrLf & strRet
    6.    Next
    7. End If

  18. #18
    PowerPoster dilettante's Avatar
    Join Date
    Feb 2006
    Posts
    24,487

    Re: vbNullString vs ""

    With InputBox you get vbNullString returned on Cancel as already described, but it is true you can't use a String value comparison (i.e. S = vbNullString) to detect it:
    Code:
        Dim S As String
        
        S = InputBox("Enter a value to proceed")
        If StrPtr(S) = 0 Then
            Print "1: User canceled"
        ElseIf Len(S) = 0 Then
            Print "2: Empty input"
        ElseIf Len(Trim$(S)) = 0 Then
            Print "3: All blank input"
        Else
            Print "4: Non-blank input"
        End If
    Arguably the difference between 3 & 4 or even 2 & 4 is in the eye of the beholder, but case 1 (Cancel) is distinct from the others.

    A dialog Cancel button is not meant to signify "empty input" but more of a "don't go ahead with this operation" action. Another example might be the Cancel button of a File Open dialog.

    The vbNullString constant can be used to return a distinct null value from your own String valued Functions too. It has a role similar to that of the Variant Null value returned from database fields.

    That's the other role of vbNullString: parameters passed to API calls that distinguish a null String value from a 0-length value.

    As for testing a String for being of zero length goes, after a decade of back and forth we've settled in our shop:
    • S = vbNullString is considered "profanity" and will fail in code reviews
    • S = "" is considered bad form and costs you a point for every ocurrence
    • Len(S) = 0 is the only accepted form

    Not all of us agree with those rules, and if we were only writing VB6 we might fight harder. But the history of bonehead errors that slipped into production because somebody used vbNullString in a comparison when they meant to test StrPtr(S) = 0 keeps us quiet.

  19. #19
    Head Hunted anhn's Avatar
    Join Date
    Aug 2007
    Location
    Australia
    Posts
    3,669

    Re: vbNullString vs ""

    From Object Browser:
    Const vbNullString = ""
    also:
    Const vbNullChar = ""

    But: StrPtr(vbNullString) = 0, and StrPtr("") <> 0 (as mentioned above) ???!!!???

    Why?!?

    There is no relation between Chr$(0) and vbNullString or "" (LaVolpe's post#2):
    Len(Chr$(0)) = 1
    Len(vbNullString) = 0
    Len("") = 0
    • Don't forget to use [CODE]your code here[/CODE] when posting code
    • If your question was answered please use Thread Tools to mark your thread [RESOLVED]
    • Don't forget to RATE helpful posts

    • Baby Steps a guided tour
    • IsDigits() and IsNumber() functions • Wichmann-Hill Random() function • >> and << functions for VB • CopyFileByChunk

  20. #20
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: vbNullString vs ""

    Don't just look at the Const line of the object browser (which doesn't display unprintable characters, pointers, etc), look at the description too

    vbNullChar is described as Chr$(0), and has a very different purpose

    unfortunately the description of vbNullString is not quite as clear - as LaVolpe showed earlier it is a string with a pointer (memory location) of 0; some C functions require that, and there is no reasonable way to create it with VB (all actual strings need a valid memory location). For the purposes of comparison/concatenation/string functions/etc within VB, vbNullString is treated the same as an empty string.

  21. #21
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: vbNullString vs ""

    A little more fun with this topic. You will notice that uninitialized strings are in fact Nulls (StrPtr of Zero).
    Code:
    Dim A as String, B as String
    B = ""
    Debug.Print StrPtr(A), StrPtr(B)
    Regading the Chr$(0) and VB. I like how VB allows us to add null characters in a string, but at the same time not knowing that null characters can be in a string can prevent coders from getting a proper string length.

    For example. If S were a String variable and we did this:
    S = vbNullChar & "VBForums"
    What do you think the string length would be? In VB, it is Len("VBForums")+1
    For APIs & just about every other language, it is zero length. That is because just about everything except VB will expect a null-terminated string. And if the first character is null, then the string is null.

    This is where the BString format comes in. The BString format will have a 4 byte header in front of string data. That header says how many actual bytes of string data follow. VB uses BStrings.

    To prove my point, try adding this to a listbox:
    Code:
    Private Sub Command1_Click()
        Dim s As String
        s = vbNullChar & "VBForums"
        List1.AddItem s
        Debug.Print "ListBox Item 0 is [" & List1.List(0) & "] ' will be 'blank' []
        Debug.Print "Len(VBForums) = "; Len("VBForums")
        Debug.Print "Len(vbNullChar + VBForums) = "; Len(s)
    End Sub
    This is why many times when APIs are used that return a string, we may need to look for vbNullChar within VB's string to get the true length of the string returned by the API (or use the API equivalent).

    Edited: Now there may be some out there that say "Hey, VB is just sending a zero length string to the listbox because it will convert it to ANSI. before calling SendMessage to update the listbox, and probably truncates the string first." Ok, but if you sent a byte array of 9 values to the ListBox via API, making the first byte 0, you'd get the same results too.

    And of course not all APIs will treat this the same as some may expect a null-delimited string, while others may expect you to provide the string length in another parameter for example.
    Last edited by LaVolpe; Jan 28th, 2009 at 09:18 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  22. #22
    PowerPoster ThEiMp's Avatar
    Join Date
    Dec 2007
    Location
    Take The PCI Bus Across To The CPU!!
    Posts
    3,948

    Re: vbNullString vs ""

    Instead of using vbNullString, then you can use the variable control string command as Nothing.

    For example:
    Set Item1 = Nothing

    Okay, and then adapt that to your project. You can use that perfectly in just about every circumstance that might arise, in programming in VB6. I also think, that it could work in later, and future versions of VB or VS as well, as in this version.
    I have a huge free products range, of computer software in which you can download using any kind of 64-Bit Web Browser. Also there is coming a Social Networking section that I am making on my Website...

    |Ambra Productions Inc. | The Black Sun Society | The Black Shield | Ambra College | Church of the Black Sun | Ambra Productions Inc's Homepage | Boomtick Venues: Ambar Nightclub, Jack Rabbit Slim's, Villa Nightclub and Lucy's Love Shack | Pasta Ambra | Fish Feast Company | Wallet Wizard | Ambrose Liquor | Ambar Tavern | Ambra University | Ambra Cheese |

    Do you wish to do unpaid work for me??? If so, the PM me on this Forum, and then we can get to work, programming for the future of computers go by the name of ThEiMp. This is my ghost writers name. Also my nickname, means that I am: The Imperial of the Technology Industry, so then to make it really short, I just then wrote: The Imp, which is where I get the nickname from...

  23. #23
    PowerPoster CDRIVE's Avatar
    Join Date
    Jul 2007
    Posts
    2,620

    Re: vbNullString vs ""

    Quote Originally Posted by ThEiMp
    Instead of using vbNullString, then you can use the variable control string command as Nothing.

    For example:
    Set Item1 = Nothing
    I don't believe that's what's being discussed here. Set Item1 = Nothing destroys an instance of an object.
    <--- Did someone help you? Please rate their post. The little green squares make us feel really smart!
    If topic has been resolved, please pull down the Thread Tools & mark it Resolved.


    Is VB consuming your life, and is that a bad thing??

  24. #24

    Thread Starter
    PowerPoster isnoend07's Avatar
    Join Date
    Feb 2007
    Posts
    3,237

    Re: vbNullString vs ""

    thanks for all the feedback everyone, This has made me change the way i do checking:
    For strings:
    gonna start using Trim
    If Trim(text1) = "" then 'in case someone pressed the spacebar

    For numbers:
    If val(text1) = 0 then 'anything but a number will be 0
    Waiting for a full featured smart phone with out marrying a provider
    Go Android
    Go raiders

  25. #25
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: vbNullString vs ""

    Quote Originally Posted by isnoend07
    thanks for all the feedback everyone, This has made me change the way i do checking:

    For numbers:
    If val(text1) = 0 then 'anything but a number will be 0
    Not really. The number 0 will still be zero.
    Val("1313 Mockingbird Lane") = 1313

    What about using IsNumeric?
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  26. #26
    PowerPoster CDRIVE's Avatar
    Join Date
    Jul 2007
    Posts
    2,620

    Re: vbNullString vs ""

    Since this is such an interesting and informative topic perhaps a link to it should be created in Tips & Tricks or whatever.
    <--- Did someone help you? Please rate their post. The little green squares make us feel really smart!
    If topic has been resolved, please pull down the Thread Tools & mark it Resolved.


    Is VB consuming your life, and is that a bad thing??

  27. #27

    Thread Starter
    PowerPoster isnoend07's Avatar
    Join Date
    Feb 2007
    Posts
    3,237

    Re: vbNullString vs ""

    Quote Originally Posted by LaVolpe
    Not really. The number 0 will still be zero.
    Val("1313 Mockingbird Lane") = 1313

    What about using IsNumeric?
    Thanks for your reply
    For my purposes Val works fine as the fields being checked only allow numbers
    also
    Isnumeric(2,4,5,6,3) = true
    Waiting for a full featured smart phone with out marrying a provider
    Go Android
    Go raiders

  28. #28
    PowerPoster CDRIVE's Avatar
    Join Date
    Jul 2007
    Posts
    2,620

    Re: vbNullString vs ""

    Quote Originally Posted by isnoend07
    Thanks for your reply
    For my purposes Val works fine as the fields being checked only allow numbers
    also
    Isnumeric(2,4,5,6,3) = true
    So will &H(n).
    <--- Did someone help you? Please rate their post. The little green squares make us feel really smart!
    If topic has been resolved, please pull down the Thread Tools & mark it Resolved.


    Is VB consuming your life, and is that a bad thing??

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width