The Excel VBA LEN function counts the number of characters in a string or variable. It returns a Long data type representing the character count. To use it, you simply pass the string or variable name into the function as an argument. For example, MsgBox Len("Hello World") will display 11 in a message box.

What You'll Need

  • A computer running Microsoft Windows with Microsoft Excel installed.
  • A basic understanding of how to open the Visual Basic for Applications (VBA) editor.
  • Access to the Developer tab in the Excel ribbon (if you need to run the macro).

Step-by-Step

  1. Open the VBA Editor. In Excel, press Alt + F11 on your keyboard. This shortcut opens the dedicated VBA development environment window. If you do not see the keyboard shortcut working, navigate to the Developer tab on the Excel ribbon and click the Visual Basic button.
  2. Insert a New Module. In the VBA editor, look for the menu item Insert at the top of the window. From the dropdown, select Module. A new, empty code window will appear on the right side of the screen. This window is where you will write your code.
  3. Check Reference Settings (Optional but Recommended). For the LEN function to work correctly with Excel ranges, you must ensure the Excel Object Library is referenced. In the VBA editor, go to the menu Tools and select References. In the list that appears, look for a checkbox next to Microsoft Excel X.X Object Library (where X.X is your version number, e.g., 16.0). Ensure this box is checked. If it is not checked, the code will likely fail when trying to pass a range object to the Len function.
  4. Write the Basic Function. Return to your empty module window. Type the following code to create a function named GetStringLength. This function takes a single argument, TextToCheck, and returns the length using the LEN function.
    Function GetStringLength(TextToCheck As Variant) As Long
        ' The Len function handles both strings and numbers automatically
        GetStringLength = Len(TextToCheck)
    End Function

    Note: The Variant data type is used for the argument to allow the function to accept both text typed directly into the cell and references to cells containing data.

  5. Prepare the Test Data. Return to your main Excel worksheet. Select a cell, such as A1, and type a word or phrase. For example, type Apple. You will use this data to test your function in the next step.
  6. Call the Function from Excel. In a different cell, say B1, type an equals sign = followed by the name of your function and the cell reference. It should look like this: =GetStringLength(A1). Press Enter. The cell B1 should now display the number 5, which is the length of the word "Apple".
  7. Test with Numbers. Change the value in cell A1 to a number, such as 12345. Press Enter. The LEN function counts the digits as characters, so B1 will correctly display 5. This demonstrates that the function works with numeric data as well as text.
  8. Test with Empty Cells. Clear the value in cell A1. Leave it empty. Press Enter. The function will return 0. This confirms that the function handles null or empty inputs gracefully without generating an error.
  9. Test with VBA Immediate Window. Return to the VBA editor. Open the Immediate Window by pressing Ctrl + G or navigating to View > Immediate Window. Type the following line of code into the window and press Enter: Debug.Print Len("Test String"). The result 11 will appear in the Immediate Window. This is a quick way to debug values while writing your script.

Common Mistakes

  • Confusing LEN with COUNTA. A common error is using the LEN function when you actually need the COUNTA function. LEN counts characters. COUNTA counts non-empty cells. If you have a cell that looks empty but contains a space character, LEN will return 1, while COUNTA will return 1 (because the cell is not empty). If you want to know how many cells have data in a range, use COUNTA, not LEN.
  • Forgetting to Set the Data Type. If you define the function argument as a String, LEN will throw a Type Mismatch error if you try to pass it a numeric value. Always use the Variant data type for the argument, as discussed in Step 4, to ensure the function accepts both text and numbers without crashing.
  • Ignoring Hidden Characters. The LEN function counts every single character, including spaces, tabs, and line breaks. If your string length is reporting a number higher than you expect, it is likely due to a hidden space or line break at the end of the string. You may need to use the TRIM function to clean the data before checking its length.
  • Passing a Range Object Directly. In VBA, you cannot pass a Range object directly to a function that expects a String or Variant without handling the conversion. You must use the Value property of the range, e.g., Len(Range("A1").Value). If you simply write Len(Range("A1")), VBA will throw a runtime error 13: Type Mismatch.

Tips

  • Use LEN for Validation. You can use the LEN function to create data validation rules. For example, you can write a VBA script that checks if a user input is longer than a certain number of characters before saving the data. This is useful for enforcing password complexity or limiting the length of customer comments.
  • Check for Null Values. If you are processing data from a database or a user input form, there is a chance the variable might be Null rather than an empty string. You should always check for Null before using LEN, or use the IIf function to return a default value. For example: IIf(IsNull(Variable), 0, Len(Variable)).
  • Combine with Other String Functions. LEN is often used in conjunction with other string functions like Left, Right, and Mid. For instance, you can use LEN to determine how many characters are in a cell, and then use that number to extract a specific substring. This is particularly useful for parsing fixed-width text files.
  • Optimize for Performance. If you are looping through thousands of rows of data to check the length of each cell, avoid calling the LEN function inside the loop if possible. Instead, read the range of data into a 2D array first, process the data in the array using LEN, and then write the results back to the worksheet. This approach is significantly faster because it minimizes the communication between the VBA code and the Excel worksheet.

Troubleshooting

If your LEN function is not working as expected, proceed through these checks in order.

First, check the reference. If you are trying to pass a cell reference or a Range object to your function, and you are getting a Type Mismatch error, the issue is almost certainly that the Excel Object Library is not referenced. Go back to Tools > References in the VBA editor and ensure the checkbox for Microsoft Excel Object Library is checked.

Next, check for hidden characters. If you are comparing the length of a string that you typed manually with the result of a formula, and the result is one character higher than expected, the string likely contains a hidden space. You can verify this by pasting the text into a text editor like Notepad. If the text wraps to a new line in Notepad, it contains a line break character. Use the Replace function in VBA to remove these unwanted characters.

Then, check the data type. If you are receiving a Compile Error or a Run-time Error, double-check the data type of your function argument. If you declared it as a String but are passing it a number, the code will fail. Change the data type to Variant to allow for both text and numbers.

Finally, check for Null. If your function returns a blank or an error when processing a specific variable, the variable might be Null. This often happens when reading data from a database or an external source. Add a check using the IsNull function to handle this case gracefully. If the variable is Null, you can return 0 or a default message instead of crashing.

Frequently Asked Questions

Does the LEN function count spaces?

Yes, the LEN function counts every character in the string, including spaces, tabs, and line breaks. It does not automatically trim whitespace.

Can I use LEN on a whole range of cells?

You cannot pass a range of cells directly to the LEN function. You must loop through the range and apply the LEN function to each cell individually, or use the SUMPRODUCT function in a worksheet formula (e.g., =SUMPRODUCT(LEN(A1:A10))).

What does the function return if the input is empty?

If the input is an empty string ("") or an empty cell, the LEN function will return 0. It will not return an error.

Why does my function return a #VALUE! error?

A #VALUE! error in a worksheet formula usually means you are trying to pass a non-text value (like a number) to a function that is expecting text, or you are using the function inside a cell incorrectly. In VBA, a Type Mismatch error means you are passing the wrong data type to the function.

Is the VBA LEN function the same as the Excel LEN function?

Yes, they are identical in syntax and behavior. The VBA function is a direct port of the Excel worksheet function.