GCC
GCC

Reputation: 295

How to highlight a cell based on another cells value VBA?

This question has been asked before but I went about doing it another way. I am trying to highlight a cell if it is greater than the value of another cell.

Here is my code:

Sub Error_Search()

Dim Summary As Worksheet
Dim lr As Long
Set Summary = Worksheets("Summary")


            lr = Cells(Rows.Count, 20).End(xlUp).Row

    With Summary

            For i = lr To 3 Step -1

            If Range("L" & i).Value > Range("$Q$2:$R$3").Value Then Range("L" & i).Font.Color = -16776961

            Next i

    End With

End Sub

Range("$Q$2:$R$3") is a merged cell and it is the cell I want to compare the cell I want to highlight to.

I keep getting a mismatch error.

Any help would be greatly appreciated.

Thanks,

G

Upvotes: 1

Views: 2249

Answers (1)

Mathieu Guindon
Mathieu Guindon

Reputation: 71227

As mentioned in the comments, the problem is that a multiple-cells Range doesn't have a single Value, even if the cells are merged: Range.Value yields a 2D variant array whenever more than a single cell is involved. So you can fix the bug by only referring to the top-left cell of the merged range instead.

That said...

You don't need any VBA code to do this; conditional formatting handles it quite neatly.

Conditional format formula: =$C4>$M$3

 =$C4>$M$3

Note the $ dollar signs: $M$3 would be your merged cell (only the leftmost cell matters), and $C4 is just the first cell you're defining the conditional format into; leaving the row non-absolute (i.e. no $ on the row number) allows you to apply the format to an entire range of cells by specifying the Applies to range:

cells in $D:$L where $C is greater than $M$3 are highlighted

Note that the format formula is the same regardless of whether we're looking at $M$3 or $M$3:$N$3 merged cells.

Conditional formats will perform much better than any VBA code you can write.

Upvotes: 1

Related Questions