5

Below is VBA code to color cells if the last character or first character is a space.

I tried a test file and it worked, but on the file that has to be checked, an error message appears:

"Run-time error '13': Type mismatch".

If I click on debug, the yellow text line to show the error jumps to

If Left(sheetArr(i, j), 1) = " " Then

I checked my worksheet and the naming is correct.

I have thousands of cells to check. I may not modify cells, I may only add macros to check things because this file will be used by other departments.

Sub trailingspace()
'
' Find preceding and trailing spaces in a cell.
' Color these cells pink.
'

    Dim i As Long, j As Long
    Dim sh As Worksheet
    Dim sheetArr As Variant
    Set sh = ThisWorkbook.Sheets("wording")
    sheetArr = sh.UsedRange
    rowC = sh.UsedRange.Rows.Count
    colC = sh.UsedRange.Columns.Count

    For i = 1 To rowC
        For j = 1 To colC
            If Left(sheetArr(i, j), 1) = " " Then
                sh.Cells(i, j).Interior.ColorIndex = 26
            End If

            If Right(sheetArr(i, j), 1) = " " Then
                sh.Cells(i, j).Interior.ColorIndex = 26
            End If
        Next j
    Next i
End Sub
2
  • let's try: change sheetArr(i, j) to sheetArr.cells(i,j) . use Or operator to shorten the code. Commented Jan 22, 2020 at 8:54
  • 1
    Don't loop over all these cells. Either, look into conditional formatting OR use ReplaceFormat. Also, rather avoid UsedRange since it can return unwanted results.
    – JvdV
    Commented Jan 22, 2020 at 8:55

3 Answers 3

5

Here is another alternative that avoids VBA entirely. I decided against using a formula that would include both leading and trailing spaces and separated out the rules just in case you (or someone looking at this question later) wanted a different format for each rule.

  • Start by selecting the range you want to be checked for formatting.
  • Create a new CF rule, selecting the 2nd option "Format only cells that contain".
  • In the first dropdown box, select "Specific Text"
  • In the 2nd box, select "beginning with"
  • In the formula box, simply type a space
  • Then select your desired formatting (which in your case, will be a pink fill)
  • Repeat the steps above, except using "ending with" in this iteration

In the end, your result would look like the following:

enter image description here

2

As per my comment, I think this could be either a case for conditional formatting, or ReplaceFormat to prevent iteration over all these cells. Keep in mind UsedRange is unreliable too (and probably the cause of unreliable dimensions you calling your array with > yielding your error). So maybe try something like below:

Sub Test()

Dim lr As Long, lc As Long, rng As Range

With ThisWorkbook.Sheets("wording")

    'Get last used row and column
    lr = .Cells(.Rows.Count, 1).End(xlUp).Row
    lc = .Cells(1, .Columns.Count).End(xlToLeft).Column

    'Set your range object
    Set rng = .Range(.Cells(1, 1), .Cells(lr, lc))

    'Set your ReplaceFormat
    With Application.ReplaceFormat
        .Clear
        .Interior.ColorIndex = 26
    End With

    'Replace formatting to cells with trailing and leading spaces
    rng.Replace What:=" *", Replacement:="", SearchFormat:=False, ReplaceFormat:=True
    rng.Replace What:="* ", Replacement:="", SearchFormat:=False, ReplaceFormat:=True

End With

End Sub
2

You can just apply a conditional formatting for the range you want to check using the following formula:

=OR(LEFT(A1,1)=" ",RIGHT(A1,1)=" ")

or add the condition using VBA

rng.FormatConditions.Add Type:=xlExpression, Formula1:="=OR(LEFT(A1,1)="" "",RIGHT(A1,1)="" ""))"
rng.FormatConditions(rng.FormatConditions.Count).SetFirstPriority
With rng.FormatConditions(1)
    .Interior.PatternColorIndex = xlAutomatic
    .Interior.ThemeColor = xlThemeColorAccent2
    .Interior.TintAndShade = 0
    .FormatConditions(1).StopIfTrue = False
End With
4
  • From the VBA perspective, this would probably be my preferred solution as it incorporates conditional formatting. This means the code would not have to run every time a change has been made. Commented Jan 22, 2020 at 9:20
  • 1
    @K.Dᴀᴠɪs. Do realize condtional formatting is volatile and always "runs" =). But yes, I agree. CF is a very nice alternative.
    – JvdV
    Commented Jan 22, 2020 at 9:22
  • 1
    @JvdV but at least in can make use of multi-threading while VBA cannot :)
    – Pᴇʜ
    Commented Jan 22, 2020 at 9:23
  • 1
    You are very correct, @JvdV! However, imagine placing OP's code into a worksheet change event! Commented Jan 22, 2020 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.