Home » excel » excel – Highlight cells with spaces before and after values

excel – Highlight cells with spaces before and after values

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have created a small macro for highlighting cells with more than one spaces in names. Now I have noticed that there are also values with space before the name and after. How to edit my current code so it will highlight cells also like ” Word word” or “Word word” or ” Word word “

So the only one that will pass the validation is case when everything is properly written like “Word word”

Here is my current code:

Sub MarkMoreThanOneSpace()

Dim Cell
Dim rng As Range

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

    Set rng = ThisWorkbook.Worksheets("Main").Range("A2:L" & ThisWorkbook.Worksheets("Main").Range("A2").End(xlDown).Row)

    For Each Cell In rng
    If WorksheetFunction.CountIf(Cell, "*  *") > 0 Then

        Cell.Interior.ColorIndex = 6

    Exit Sub
    End

    End If

    Next Cell

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub
How to&Answers:

you could use WorksheetFunction.Trim() function

loop through cells with values only to shorten time

don’t exit at the first finding, or you’ll miss all the others

and don’t use End!

Sub MarkMoreThanOneSpace()

    Dim cell As Range
    Dim rng As Range

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set rng = ThisWorkbook.Worksheets("Main").Range("A2:L" & ThisWorkbook.Worksheets("Main").Range("A2").End(xlDown).Row)

    For Each cell In rng.SpecialCells(xlCellTypeConstants)
        If WorksheetFunction.Trim(cell.Value) <> cell.Value Then cell.Interior.ColorIndex = 6
    Next

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub

Answer:

This should work. Also, you can try Regex, but that may be overkill.

If WorksheetFunction.CountIf(Cell.Value, "*  *") > 0 _
    Or Left$(Cell.Value,1) = " " _
    Or Right$(cell.Value,1) = " " Then

Furthermore, you can get rid of VBA altogether and place these formulas in conditional formatting rules.