Why is this a problem
Imagine you have a column of data, containing the values "Red", "Green" and "Blue", which a user has entered manually. Except the user has entered some extra spaces after some of the values so that your column of data (column A) looks like this:
Red
Green
Green
Blue
Green[space]
Blue
Red[space]
Red
Green
I then create a formula to count the number of cells containing the value "Green", like so:
=COUNTIF(A:A,"Green")
How many will there be? It will tell me there are 2. Why? Because "Green[space]" is not the same as "Green" in Excel.
So as you can see, it becomes important to prevent users adding extra spaces after their data.
How do we stop them?
We can prevent leading or trailing spaces using Custom Data Validation. Here are the steps to work through...
- Select the column you want to protect.
- Click on "Data Validation" on the Data tab.
- In the dialogue that pops up, choose "Custom".
- Enter the following formula into the box, replacing the references to "A1" with the first cell in your range: =TRIM(A1)=A1
A caution...
Unfortunately, Data Validation in Excel doesn't prevent people pasting incorrect values into the cell - only typing manually. There are 2 work-arounds for this, which we'll look at in future blog posts:
- Prevent people pasting anything into the sheet using a Macro, or
- Set up Conditional Formatting to show if cells have trailing spaces which have been pasted in.
Get our Excel tips direct to your inbox and make sure you never miss a top tip - fill in your details just here.