TOP

VBA Function: Len

Description

The VBA LEN Function returns the number of characters in a string.


LEN Syntax

Len(text)

VBA Len Example

Get the character count of multiple strings:

Sub LenExample1()

     MsgBox Len("")                     'Returns: 0
     MsgBox Len("45")                   'Returns: 2
     MsgBox Len("excel")                'Returns: 5
     MsgBox Len("www.moonexcel.com.ua") 'Returns: 20
    
     variable = "moonexcel"
     MsgBox Len(variable) 'Returns: 9
    
End Sub

Using the Len function in a condition that checks that the username has at least 3 characters before performing an action:

Sub LenExample2()

     name = InputBox("Enter username:", "Name")
    
     If Len(name) >= 3 Then
         MsgBox "Well done " & name & "!"
     End If
    
End Sub