【发布时间】:2020-03-07 03:40:42
【问题描述】:
我有一个代码将两个条件格式规则添加到工作表 4(列 A2:A 和最后一行),现在我试图突出显示活动行直到最后一列(例如,列 B:E活动行)。目前我有这个代码:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$2" Then
Dim lr As Long
lr = Range("A" & Sheet4.rows.Count).End(xlUp).Row
With Range("A2:A" & lr)
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, Operator:=xlExpression, Formula1:="=COUNTIF('Test 2'!$A:$A,A2)>0"
.FormatConditions(1).Interior.Color = RGB(198, 239, 206)
.FormatConditions.Add Type:=xlExpression, Operator:=xlExpression, Formula1:="=COUNTIF('Test 2'!$A:$A,A2)=0"
.FormatConditions(2).Interior.Color = RGB(255, 199, 206)
End With
End If
End Sub
我有两种可能的解决方案
(1) 将条件格式添加到 A 列之后的活动行(例如活动行的 B:E。我在上面代码中的 End If 之后使用此代码。
If Application.CutCopyMode = False Then
Application.Calculate
End If
With Target
.FormatConditions.Add Type:=xlExpression, Operator:=xlExpression, Formula1:="=CELL("row")=ROW()"
.FormatConditions(1).Interior.Color = RGB(220, 239, 206)
End With
条件格式的公式.FormatConditions.Add Type:=xlExpression, Operator:=xlExpression, Formula1:="=CELL("row")=ROW()" 似乎出现错误
(2) 我已经添加了一行来将活动行中列 A 的名称定义为“MyRange”以用于其他目的,因此我现在也尝试添加此代码而不是条件格式:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveWorkbook.Names.Add Name:="MyRange", RefersToR1C1:=Range("A" & (ActiveCell.Row))
Range("A" & (ActiveCell.Row)).Select 'Always Selects Column A depending on the Active Row selected
Range("B:E" & (ActiveCell.Row)).Interior.Color = RGB(243, 243, 123)
End Sub
第二个解决方案的错误是Range("B:E" & (ActiveCell.Row)).Interior.Color = RGB(243, 243, 123)
【问题讨论】:
-
我会在这里走
Selection Change路线,但可能有比您目前尝试的更简单的方法。 -
是的,我同意,
Selection Change似乎是一条更好的路线,并且看到我已经将它用于Range("A" & (ActiveCell.Row)).Select用于另一个目的,我想以某种方式将它添加到这里。你知道为什么它可能不起作用吗? -
"B:E" & (ActiveCell.Row)没有为您提供有效的范围参考。您需要为每一列重复行号,因此输出类似于B5:E5。 -
我同意,我找到了一个可行的解决方案,见下文
标签: excel vba autofilter