[英]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. Range(“ $ Q $ 2:$ R $ 3”)是一个合并的单元格,它是我要比较要突出显示的单元格的单元格。
I keep getting a mismatch error. 我不断收到不匹配错误。
Any help would be greatly appreciated. 任何帮助将不胜感激。
Thanks, 谢谢,
G 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. 如注释中所述,问题在于即使合并了单元格,多个单元格的
Range
也不具有单个Value
:只要涉及的单元格超过一个, Range.Value
生成2D变量数组。 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; 您不需要任何VBA代码即可执行此操作; conditional formatting handles it quite neatly.
条件格式可以非常整洁地处理它。
=$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; 注意$符号:
$M$3
将是您合并的单元格(只有最左边的单元格很重要),而$C4
只是您将条件格式定义为的第一个单元格; 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: 保留非绝对行(即行号上没有$),可以通过指定“ 应用于范围”将格式应用于整个单元格范围:
Note that the format formula is the same regardless of whether we're looking at $M$3 or $M$3:$N$3 merged cells. 请注意,无论我们要查看的是$ M $ 3还是$ M $ 3:$ N $ 3合并的单元格,格式公式都是相同的。
Conditional formats will perform much better than any VBA code you can write. 条件格式的性能将比您可以编写的任何VBA代码都要好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.