How to check the length of text with IF in Excel
Formula (Excel and Google Sheets)
=IF(LEN(A2)=$E$1,"OK","Wrong length")Compare LEN with the required length: =IF(LEN(A2)=$E$1,"OK","Wrong length").
- Result on the example
- one result per row in
B2, filled down toB7 - Works in
- Every current version
- Google Sheets
- Same formula
See it work
The formula is already in B2, filled down to B7. Change any input and the result updates, or edit the formula to experiment.
How it works
LEN counts every character, letters, digits, spaces and punctuation alike. IF compares the count with the required length kept in E1. "AC 3041" has 7 characters including the space.
=IF(LEN(A2)=$E$1,"OK","Wrong length")Result"OK"
A2"AC104522"The value in A2.
LEN(A2)8LEN: Number of characters.- text
A2"AC104522"
- text
$E$18The value in E1.
LEN(A2)=$E$1TRUEThe = operator tests whether the two sides are equal.
IF(LEN(A2)=$E$1,"OK","Wrong length")"OK"IF: Returns one value if a test is true, another if false.- logical_test
LEN(A2)=$E$1TRUE - value_if_true
"OK" - value_if_false
"Wrong length"not used
- logical_test
In Google Sheets
The same formula works in Google Sheets: =IF(LEN(A2)=$E$1,"OK","Wrong length"). We ran it in Google Sheets mode on the same data and it returns the same results.
Other ways to do it
Each one was run on the same example sheet.
| Formula | Result | When to use it |
|---|---|---|
| =IF(LEN(TRIM(A2))=$E$1,"OK","Wrong length") | OK, Wrong length, Wrong length… | Ignores leading and trailing spaces, which imports often add. |
| =LEN(A2) | 8, 7, 9…Different result | The length itself, to see how far off each ID is. Shows 8, 7, 9, 8, 7 and 8. |
Common mistakes
- LEN counts spaces and punctuation, so a stray space makes a valid-looking ID the wrong length.
- Numbers lose leading zeros: an ID typed as 00123 is stored as 123, which has 3 characters. Store IDs as text.
Try it yourself
Same data, empty answer cell. Your formula is graded instantly, then re-checked on changed data, so a typed-in number won't pass.
Check the length of text with IF
B2, show "OK" when the ID has exactly the number of characters in E1, otherwise "Wrong length". Fill down to B7.Questions
How do I allow a range of lengths?
=IF(AND(LEN(A2)>=8,LEN(A2)<=10),"OK","Wrong length").
How do I enforce the length while typing?
Use Data Validation with Text length, equal to 8.
Checked by running on 2026-10-30: every formula and result on this page was calculated by the Spreadsheet Practice formula engine, in both Excel and Google Sheets modes.