Name

Len, LenB Functions

Syntax

Len(string | varname)
string

Use: Required

Data Subtype: String

A valid string expression.

varname

Use: Required

Data Subtype: Any except object

A valid variable name.

Return Value

A Variant with subtype Long.

Description

Counts the number of characters within a string or the size of a given variable. Use LenB to determine the actual number of bytes required to hold a given variable in memory.

Rules at a Glance

  • string and varname are mutually exclusive; that is, you must specify either string or varname, but not both.

  • If either string or varname contains Null, Len returns Null.

  • When you use LenB with byte data or a Unicode string, LenB returns the number of bytes that represent the data or the string.

  • You can’t use Len with an object variable.

  • If varname is an array, you must also specify a valid subscript. In other words, Len can’t determine the total number of elements in or the total size of an array.

Programming Tips & Gotchas

  • Nonstring variants are treated the same as a string variables, and Len returns the actual number of characters stored to the variable. But this can lead to unexpected results. Take the following snippet as an example:

    Dim vVar
    vVar = 100
        
    MsgBox Len(vVar)

    You may expect the Len function to return 2 because iVar is obviously a variant of subtype integer. In fact, Len returns 3: the number of characters contained within the variant. In other words, the Len and LenB functions, when used with nonstring variants, return the number of characters ...

Get VBScript in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.