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 ?
Printable View
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 ?
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 ("")
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.
So i guess they both do the same thing check for nothing entered
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
An alternative is...Edit: oops did not see you there martin which means an embarrassing 7 minutes plus to post one line, sheeshCode:If Lenb(String) Then 'String is neither zero length nor none existent
Yes and no...Quote:
Originally Posted by isnoend07
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.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
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
I think there is a difference in thinking here, kind of mind bendingQuote:
Originally Posted by Milk
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
To test if it is "blank", test for = not <> ;)Quote:
Originally Posted by MartinLiss
There are several ways to do the comparisonQuote:
Originally Posted by isnoend07
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
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
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.
I like to use the following especially in textboxes:
This will prevent the space from being savedCode:If LEN(TRIM(FromEmailAddress)) = 0 Then . . . .
It's been so long since i wrote the code i went and looked and have a lot ofQuote:
Originally Posted by leinad31
If val(.textmatrix(2,3)) <> 0 or val(.textmatrix(3,3)) <> 0 then
if the cell is empty it will return 0
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! :)
You can also use 'IsNull' where appropriate. i.e. to check a variant string array:
vb Code:
If IsNull(varRet) Then txtMsgs.Text = "Meh!" Else For Each strRet In varRet txtMsgs.Text = txtMsgs.Text & vbCrLf & strRet Next End If
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:
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.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
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.
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 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.
A little more fun with this topic. You will notice that uninitialized strings are in fact Nulls (StrPtr of Zero).
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.Code:Dim A as String, B as String
B = ""
Debug.Print StrPtr(A), StrPtr(B)
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:
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).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
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.
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 don't believe that's what's being discussed here. Set Item1 = Nothing destroys an instance of an object.Quote:
Originally Posted by ThEiMp
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
Not really. The number 0 will still be zero.Quote:
Originally Posted by isnoend07
Val("1313 Mockingbird Lane") = 1313
What about using IsNumeric?
Since this is such an interesting and informative topic perhaps a link to it should be created in Tips & Tricks or whatever.
Thanks for your replyQuote:
Originally Posted by LaVolpe
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).:)Quote:
Originally Posted by isnoend07