Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colouring cells if last or first character is a space

Tags:

excel

vba

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
like image 864
Jesse Avatar asked Jan 22 '20 08:01

Jesse


People also ask

How do you color a cell based on a condition?

Select the range of cells, the table, or the whole sheet that you want to apply conditional formatting to. On the Home tab, click Conditional Formatting, and then click New Rule. Select a style, for example, 3-Color Scale, select the conditions that you want, and then click OK.

How do you highlight cell color based on value?

Quick formatting On the Home tab, in the Style group, click the arrow next to Conditional Formatting, and then click Highlight Cells Rules. Select the command you want, such as Between, Equal To Text that Contains, or A Date Occurring. Enter the values you want to use, and then select a format.


1 Answers

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

like image 93
K.Dᴀᴠɪs Avatar answered Sep 23 '22 15:09

K.Dᴀᴠɪs