When I run the following macro:
Sub try()
Dim num As Integer
num = 123
MsgBox Len(num)
MsgBox VBA.Len(num)
End Sub
The first Msgbox displays 2 and the second Msgbox displays 3.
If I remove the first line which says Dim num As Integer, both MsgBoxes display 3.
Can anyone explain why?
Len and LenB are not just ordinary functions, they are keywords, and as such are found on the list of VBA keywords (although LenB is only mentioned after you click through to Len).
Mid would be another example of such keyword disguised as function, whereas e.g. Left isn't on the list at all, because that is just an ordinary function.
It has to be a keyword because one of its jobs is to perform the compile-time task of determining the storage size of a variable. E.g. with private user-defined types, an ordinary function could not do that at all:
Private Type foo
a As Long
b As String
End Type
Sub TestLens()
Dim f As foo
MsgBox Len(f) ' OK
MsgBox VBA.Len(f) ' Compile time error
End Sub
The fact that the object browser brings you to VBA.Len when you press Shift+F2 on that Len(f) is both correct and misleading.
The Len(f) here does not actually call the VBA.Len function that determines the string size, it simply cannot do that because it would require coercing a private struct into a Variant. Instead it calculates the size of foo at compile time and substitutes the result as a literal constant into the executable.
In your example the Len(num) calculates the compile-time size of variable num (which is 2) and substitutes the constant 2 into the resulting object code, whereas VBA.Len(num) packs the value of num into a Variant and passes that variant to VBA.Len where it's further converted to string "123" and the length of that is returned.
It has to do with the way that VB stores integers and how the Len() function handles arguments that are not strings.
When a datatype that is not a string is passed to the Len() function, it returns the nominal number of bytes used to store the data (VB uses 2 bytes to store an integer). See the documentation for the Len function.
The Len() function will automatically cast the variant variable (which is created by assigning a value to a variable without declaring it first) as a string. The return isn't changing because the storage allocation changes (although it does; variants require 16 bytes of storage space, minimum). Since the implicitly declared variable is actually a variant type, VB will automatically change its type based on the situation. In this case, Len() expects a string so VB makes the variable a string.
You could use Msgbox Len(Cstr(num)) to cast the integer variable as a string before passing it to the Len function if your intent is to return the number of characters in your integer value.
Related
I was wondering if there is any way to access the expected data type within a function similar to an event arg. I am doubtful that this is possible, though it would be an excellent feature.
I frequently work with (old and disorganized)Mysql databases creating interfaces through VB.Net. Often I will have an optional field which contains a NULL value in the database. I am frequently dealing with errors due to NULL and dbnull values in passing data to and from the database.
To complicate things, I often am dealing with unexpected datatypes. I might have an integer zero, a double zero, an empty string, or a string zero.
So I spend a fair amount of code checking that each entry is of the expected type and or converting NULLs to zeros or empty strings depending on the case. I have written a function ncc(null catch convert) to speed up this process.
Public Function ncc(obj As Object, tp As Type) As Object 'Null Catch Convert Function...
My function works great, but I have to manually set the type every time I call the function. It would be so much easier if it were possible to access the expected type of the expression. Here is an example of what I mean.
Dim table as datatable
adapter.fill(table)
dim strinfo as string
dim intinfo as long
strinfo = ncc(table.Rows(0).Item(0),gettype(String)) 'here a string is expected
intinfo = ncc(table.Rows(0).Item(0),gettype(Long)) 'here a long is expected
It would be so much more efficient if it were possible to access the expected type directly from the function.
Something like this would be great:
Public Function ncc(obj As Object, optional tp As Type = nothing) As Object
If tp Is Nothing Then tp = gettype(ncc.expectedtype)
That way I do not have to hard code the type on each line.
strinfo = ncc(table.Rows(0).Item(0))
You can make the ncc function generic to simplify calling it:
Public Function ncc(Of T)(obj As T) As T
If DbNull.Value.Equals(obj) Then Return Nothing
Return Obj
End Function
This kind of function will be able to in some cases infer the type, but if there's any possibility of null you'll still want to include a type name (because DBNull will be the inferred type for those values). The advantage is not needing to call gettype() and so gaining a small degree of type safety:
strinfo = ncc(Of String)(table.Rows(0).Item(0))
But I think this has a small chance to blow up at run time if your argument is not implicitly convertible to the desired type. What you should be doing is adding functions to accept a full row and return a composed type. These functions can exist as static/shared members of the target type:
Shared Function FromDataRow(IDataRow row) As MyObject
And you call it for each row like this:
Dim record As MyObject = MyObject.FromDataRow(table.Rows(i))
But, you problem still exists.
What happens if the column in the database row is null?
then you DO NOT get a data type!
Worse yet? Assume the data column is null, do you want to return null into that variable anyway?
Why not specify a value FOR WHEN its null.
You can use "gettype" on the passed value, but if the data base column is null, then you can't determine the type, and you right back to having to type out the type you want as the 2nd parameter.
You could however, adopt a nz() function (like in VBA/Access).
So, this might be better:
Public Function ncc(obj As Object, Optional nullv As Object = Nothing) As Object
If obj Is Nothing OrElse IsDBNull(obj) Then
Return nullv
End If
Return obj
End Function
So, I don't care if the database column is null, or a number, for such numbers, I want 0.
So
dim MyInt as integer
Dim MyDouble As Double
MyInt = ncc(rstData.Rows(0).Item("ContactID"), 0)
MyDouble = ncc(rstData.Rows(0).Item("ContactID"), 0)
dim strAddress as string = ""
strAddress = ncc(rstData.Rows(0).Item("Address"), "")
Since in NEAR ALL cases, you need to deal with the null from the DB, then above not only works for all data types, but also gets you on the fly conversion.
I mean, you CAN declare variables such as integer to allow null values.
eg:
dim myIntValue as integer?
But, I not sure above would create more problems than it solves.
So,
You can't get exactly what you want, because a function never has knowledge of how it's going to be used. It's not guaranteed that it will be on the right-hand side of an assignment statement.
If you want to have knowledge of both sides, you either need to be assigning to a custom type (so that you can overload the assignment operator) or you need to use a Sub instead of an assignment.
You could do something like this (untested):
Public Sub Assign(Of T)(ByVal field As Object, ByRef destination As T,
Optional ByVal nullDefault As T = Nothing)
If TypeOf field Is DBNull Then
destination = nullDefault
Else
destination = CType(field, T)
End If
End Sub
I haven't tested this, so I'm not completely certain that the compiler would allow the conversion, but I think it would because field is type Object. Note that this would yield a runtime error if field is not convertible to T.
You could even consider putting on a constraint requiring T to be a value type, though I don't think that would be likely to work because you probably need to handling String which is a reference type (even though it basically acts like a value type).
Because the destination is an argument, you wouldn't ever need to specify the generic type argument, it would be inferred.
What's difference between
Len(Me.txtStartDate.Value & vbNullString) = 0
and
Len(Me.txtStartDate.Value) = 0
vbNullString is essentially a null string pointer.
Debug.Print StrPtr(vbNullString) 'prints 0
It looks equivalent to a literal "" empty string, but it's not:
Debug.Print StrPtr("") 'prints an address; 6 bytes are allocated for it
There is practically no difference between your two examples... but only because Me.txtStartDate.Value is already a String.
If you were doing this:
Debug.Print Sheet1.Range("A1").Value & vbNullString
Then you would be doing an implicit type conversion between whatever type is returned by Sheet1.Range("A1").Value (say, a Date, or a Double) by means of string concatenation, because the & operator is only used for string concatenations, and the result of that expression will be a String.
In other words, it's a rather convoluted way to do this:
Debug.Print CStr(Sheet1.Range("A1").Value)
Or, as litelite mentioned, a rather convoluted way to do this:
Len(CStr(Me.txtStartDate.Value)) = 0
You typically use vbNullString in place of an empty string "" literal, to spare uselessly allocating 6 bytes (4 for the string pointer, 2 for the null character), and to make your code unambiguously clear about your intent (e.g. "I mean an empty string, this wasn't a typo"), similar to how you would use string.Empty in C#.
What is vbNullString? It is one strange bird, which exists solely for calling functions in a DLL that were written in C (or C++).
Take a look at http://vb.mvps.org/tips/varptr/. It describes a set of (now hidden) functions in VBA (and VB6) that exist solely to allow the passing of pointers to the contents of variables, again mostly to functions in a DLL that were written in C (or any other language that does pointers).
(Technically, VBA does not do pointers, so any pointer that may be returned by a function is - technically speaking - casted to a long integer. ByRef and With do involve pointers, of course, but in hidden-behind-the-scene ways.)
In particular, try out StrPtr(vbNullString); it will return 0. If you tried instead StrPtr(""), you would get some non-zero result. The result is a pointer to where the characters of a string really are in memory. However, a pointer of 0 means something special in C (and C++) - it is often called the NULL pointer (or simply NULL, or maybe null), and it is meant to signify that a pointer points to nowhere. In C programming, sometimes a coder would like to allow a pointer parameter being NULL to mean something special for a function.
If you tried StrPtr("") a few times in a row, you'll likely get a few different non-zero results. That's because VBA is creating a brand new empty string for each try, and as weird as it seems that any memory should be used for a string that is empty, remember that a string in VBA includes a long integer that indicates the number of characters in the string.
I noticed that if I do
a = min (b,c)
I often got a warning that both b and c must be double and not integer. That's because while double can be converted to integer on the fly, the other way around doesn't work.
And the reason why it should work is because b and c is passed by reference.
However, why?
min (b,c) simply takes the smaller value of b or c and return it into a
Why should the argument is passed by ref? The function doesn't change the value of it's parameter?
Since you set vb.net as the tag:
Min() function (Math.Min) is overloaded and can take arguments of the following types: byte, decimal, single, double, signed and unsigned integers of different sizes (2, 4 or 8 bytes)
Both arguments should be of the same type, otherwise implicit conversion will take place. Your statement "That's because while double can be converted to integer on the fly, the other way around doesn't work." is not accurate; see code below.
Your statement "And the reason why it should work is because b and c is passed by reference." is not true either; see code below.
This following code should compile and run fine:
Module VBModule
Sub Main()
Console.WriteLine(Math.Min(5.1, 4))
End Sub
End Module
I am new to VB and have a simple program. I just want the program to display in a message box the number of characters in a long variable. I am using the Len() function. The code is as follows.
Try
Dim num As Long = 1230456985623145
Dim numLength As Long
numLength = Len(num)
MessageBox.Show(numLength.ToString())
Catch ex As Exception
End Try
Simple. However when i run the function, it returns a value of 8 instead of the actual value. Can anyone tell me what i'm doing wrong. Do i need to add anything else to obtain the right value
It should be like this:
Dim num As Long = 1230456985623145
Dim numLength As Long
numLength = Len(num.ToString())
MessageBox.Show(numLength.ToString())
If you forgot to use ToString(), Len function returns the number of bytes required to store the variable, which is 8 because a Long variable requires 8 byte to store.
Definition of Len function in MSDN:
Returns an integer containing either the number of characters in a
string or the nominal number of bytes required to store a variable.
In your original code (before your edit):
You use Name as a parameter in your Len function. Since your code is a WinForm, the Name is a property of the Form. Check the value of the Name using:
MessageBox.Show(Name)
String.Length
Using the Length property of a string is more preferable. Like Adrian Wragg said, it's easier to convert your codes between the languages which are supported by .Net (C#, VB and F#).
When I run the following macro:
Sub try()
Dim num As Integer
num = 123
MsgBox Len(num)
MsgBox VBA.Len(num)
End Sub
The first Msgbox displays 2 and the second Msgbox displays 3.
If I remove the first line which says Dim num As Integer, both MsgBoxes display 3.
Can anyone explain why?
Len and LenB are not just ordinary functions, they are keywords, and as such are found on the list of VBA keywords (although LenB is only mentioned after you click through to Len).
Mid would be another example of such keyword disguised as function, whereas e.g. Left isn't on the list at all, because that is just an ordinary function.
It has to be a keyword because one of its jobs is to perform the compile-time task of determining the storage size of a variable. E.g. with private user-defined types, an ordinary function could not do that at all:
Private Type foo
a As Long
b As String
End Type
Sub TestLens()
Dim f As foo
MsgBox Len(f) ' OK
MsgBox VBA.Len(f) ' Compile time error
End Sub
The fact that the object browser brings you to VBA.Len when you press Shift+F2 on that Len(f) is both correct and misleading.
The Len(f) here does not actually call the VBA.Len function that determines the string size, it simply cannot do that because it would require coercing a private struct into a Variant. Instead it calculates the size of foo at compile time and substitutes the result as a literal constant into the executable.
In your example the Len(num) calculates the compile-time size of variable num (which is 2) and substitutes the constant 2 into the resulting object code, whereas VBA.Len(num) packs the value of num into a Variant and passes that variant to VBA.Len where it's further converted to string "123" and the length of that is returned.
It has to do with the way that VB stores integers and how the Len() function handles arguments that are not strings.
When a datatype that is not a string is passed to the Len() function, it returns the nominal number of bytes used to store the data (VB uses 2 bytes to store an integer). See the documentation for the Len function.
The Len() function will automatically cast the variant variable (which is created by assigning a value to a variable without declaring it first) as a string. The return isn't changing because the storage allocation changes (although it does; variants require 16 bytes of storage space, minimum). Since the implicitly declared variable is actually a variant type, VB will automatically change its type based on the situation. In this case, Len() expects a string so VB makes the variable a string.
You could use Msgbox Len(Cstr(num)) to cast the integer variable as a string before passing it to the Len function if your intent is to return the number of characters in your integer value.