Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA Text Length: How to Count Characters

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To find the length of a text string in Excel VBA, use the Len() function. This built-in function returns an integer representing the total number of characters in a string, including spaces, punctuation, and special characters. For example, Len("Hello World") returns 11.

What You'll Need

  • Microsoft Excel installed on a Windows or Mac computer.
  • Access to the Developer tab in the Excel Ribbon.
  • A basic understanding of how to open the Visual Basic Editor (VBE).
  • A dataset containing text strings that require length validation or counting.

Step-by-Step

  1. Enable the Developer Tab: If you do not see the Developer tab at the top of your Excel window, right-click any existing tab (like Home or Insert) and select Customize the Ribbon. In the right-hand list, check the box next to Developer and click OK. Labels and menu positions may vary slightly depending on your version of Excel or region.
  2. Open the Visual Basic Editor: Click the Developer tab and select the Visual Basic button on the far left, or press Alt + F11 on your keyboard. This opens the VBE window where your code will reside.
  3. Insert a New Module: In the VBE, go to the Insert menu and select Module. This creates a blank sheet of code where you can write your macros without interfering with specific sheet or workbook objects.
  4. Write a Basic Length Check: To test the function, type the following simple macro into the module:
    Sub CheckLength()
            Dim myText As String
            myText = "Excel VBA is powerful"
            MsgBox Len(myText)
        End Sub
    This code declares a string variable, assigns it a value, and uses Len() to display the character count in a popup message box.
  5. Create a Loop for Multiple Cells: In most practical scenarios, you need to check the length of many cells. Use a For Each loop to iterate through a range. Copy and paste this example:
    Sub CountCellLengths()
            Dim cell As Range
            Dim selectedRange As Range
            Set selectedRange = Selection
            
            For Each cell In selectedRange
                'Place the length in the column immediately to the right
                cell.Offset(0, 1).Value = Len(cell.Value)
            Next cell
        End Sub
    This macro takes whatever cells you have currently highlighted in your spreadsheet and writes their character counts in the adjacent column.
  6. Implement Length Validation: If you want to flag cells that exceed a certain limit (e.g., for a database import limit of 50 characters), use an If statement:
    Sub ValidateTextLength()
            Dim cell As Range
            For Each cell In Selection
                If Len(cell.Value) > 50 Then
                    cell.Interior.Color = vbRed
                Else
                    cell.Interior.Color = vbNone
                End If
            Next cell
        End Sub
    This code scans the selected cells and highlights any that are too long in red.
  7. Run the Macro: Return to your Excel worksheet. Select the cells you wish to analyze. Go to the Developer tab, click Macros, select the macro you just wrote (e.g., "CountCellLengths"), and click Run.

Common Mistakes

One of the most frequent errors is forgetting that the Len() function counts everything. This includes leading and trailing spaces. If a user accidentally hits the spacebar after typing a word, the length will be one character longer than expected, which can cause data validation to fail. To fix this, combine Len() with the Trim() function, which removes all spaces from the start and end of a string: Len(Trim(cell.Value)).

Another common mistake is attempting to run Len() on a cell that contains an error value (such as #N/A or #VALUE!). If the VBA code encounters a cell error, the macro will crash with a "Type Mismatch" error. To prevent this, always check if the cell contains an error using IsError() before attempting to calculate the length.

Users also frequently confuse the Len function with the LenB function. While Len returns the number of characters, LenB returns the number of bytes used to represent the string. In standard English text, these are often the same, but for Unicode characters or different encoding formats, LenB will provide a different number. For 99% of text length tasks in Excel, Len is the correct choice.

Tips

To make your code more efficient when dealing with thousands of rows, avoid interacting with the worksheet inside the loop. Instead of writing the length to the cell one by one, read the entire range into a VBA array, process the lengths in memory, and write the final results back to the sheet in one single operation. This can reduce the execution time from minutes to seconds.

If you are building a user form for data entry, use the Change event of the TextBox. You can write a small piece of code that updates a label in real-time, showing the user how many characters they have left (e.g., "25/100 characters used"). This provides a much better user experience than letting them submit the form only to be told the text is too long.

Consider using Option Explicit at the very top of your module. This forces you to declare all your variables (using Dim). While it seems like an extra step, it prevents bugs caused by typos in variable names, which is the most common cause of "invisible" errors in VBA scripts.

Troubleshooting

If your macro is not running, first check if macros are enabled in your workbook. Go to File > Options > Trust Center > Trust Center Settings > Macro Settings and ensure that you have enabled macros or are using a "Disable all macros with notification" setting. If you see a yellow security warning bar at the top of the sheet, click "Enable Content".

If you receive a "Type Mismatch" error, it is likely because the code is trying to process a non-string value or a cell error. Wrap your logic in a check: If Not IsError(cell.Value) Then.... Additionally, ensure the variable you are using to store the length is an Integer or Long, as Len() always returns a numerical value, not a string.

If the character count seems incorrect, check for hidden characters. Sometimes data imported from the web contains non-breaking spaces (ASCII 160) which the standard Trim() function cannot remove. In these cases, you may need to use the Replace() function to swap Chr(160) with a standard space Chr(32) before calculating the length.

Frequently Asked Questions

Does Len count spaces?

Yes, the Len() function counts every single character within the string, including spaces, tabs, line breaks, and punctuation marks.

How do I count characters without spaces?

To count only the visible characters and exclude all spaces, use the Replace() function to remove spaces before passing the string to Len(): Len(Replace(myText, " ", "")).

What is the maximum length a string can be in VBA?

VBA strings can be very large, theoretically up to approximately 2 billion characters, though you will likely run out of system memory (RAM) long before hitting the hard limit of the string data type.

Can I use this to count words instead of characters?

No, Len() only counts characters. To count words, you typically use the Split() function to break the string into an array based on spaces and then use UBound() to count the elements in that array.

Is there a difference between Len and LenB?

Yes. Len returns the number of characters, while LenB returns the number of bytes. Because VBA uses Unicode for strings, LenB usually returns double the value of Len.

How do I handle empty cells?

If a cell is empty, Len() will return 0. If you want to skip empty cells entirely to save processing time, add a check such as If cell.Value <> "" Then before running the length calculation.