简体   繁体   中英

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

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.

条件格式公式:= $ 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 (ie no $ on the row number) allows you to apply the format to an entire range of cells by specifying the Applies to range:

$ D:$ L中$ C大于$ M $ 3的单元格突出显示

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM