Len Function

See Also2ZYFGX5              ExampleGU9XBM>Low

Returns the number of characters in a string expression1330R89 or the number of bytes required to store a variable.

Syntax 1


Syntax 2



If you use the first syntax, Len returns the number of characters in the argument strexpr.

If you use the second syntax, Len returns the number of bytes required to store a variable of the given data type3GYXY7.  If variablename is a Variant8PHEAW3, Len always returns the number of bytes required to store the Variant data as a String, regardless of the VarType7A68ZTZ.

Because Len works with user-defined data types as well as fundamental Visual Basic data types, the second syntax is particularly useful for determining record size when you are performing file input/output with random-access files.  However, if a user-defined data type contains Variant or variable-length String elements, Len may not be able to properly determine the actual number of storage bytes required.

If the argument to Len is Null1DDW7C0, the function returns a Null.

See Also

InStr FunctionPSLW56

Len Function Example

The example shows how Len can be used to return the number of bytes needed to store each fundamental Visual Basic data type.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.


Sub Form_Click ()

   Dim A As Integer, B As Long     ' Declare variables.

   Dim C As Single, D As Double

   Dim E As Currency, F As Variant

   Dim Msg, NL

   NL = Chr(10)                    ' Define newline.

   A% = 1                          ' Integer

   B& = A%                         ' Long integer

   C! = B&                         ' Single-precision, floating-point

   D# = C!                         ' Double-precision, floating-point

   E@ = D#                         ' Currency

   F = E@                          ' Variant

   Msg = "Integer values are stored in " & Len(A%) & " bytes."

   Msg = Msg & NL & "Long integer values are stored in "

   Msg = Msg & Len(B&) & " bytes." & NL

   Msg = Msg & "Single-precision values are stored in "

   Msg = Msg & Len(C!) & " bytes." & NL & "Double-precision "

   Msg = Msg & "values are stored in " & Len(D#) & " bytes."

   Msg = Msg & NL & "Currency values are stored in " & Len(E@)

   Msg = Msg & " bytes." & NL & "This Variant requires " & Len(F)

   Msg = Msg & " bytes to store it as a string." & NL

   Msg = Msg &  "This message contains "

   Msg = Msg & "more than " & Len(Msg) & " characters."

   MsgBox Msg                      ' Display message.

End Sub