使用条件格式同时自动突出显示活动行

问题描述 投票:0回答:1

我需要使用

Conditional Format
自动突出显示活动行。
以下代码仅适用于 one 活动行。
我的意思是活动行,即使用鼠标或按住 Ctrl 按钮手动选择的单元格。

Sub Highlight_active_Rows()

    Dim ws As Worksheet:    Set ws = ActiveSheet
    Dim rng As Range
    
    Set rng = ws.UsedRange.Resize(ws.UsedRange.Rows.count - 2).Offset(2)    '(UsedRange except Two Row)
    
    With rng
      .FormatConditions.Add Type:=xlExpression, Formula1:="=ROW()=CELL(""Row"")"
      .FormatConditions(rng.FormatConditions.count).SetFirstPriority
      .FormatConditions(1).Interior.Color = RGB(250, 190, 142)
      .FormatConditions(1).StopIfTrue = False
    End With 
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   Me.Range("A1").Calculate
End Sub
excel vba conditional-formatting
1个回答
0
投票

由于

Cell
公式,对于“行”
info_type
参数仅返回较大选择的左上角单元格,因此您可以将其用作条件格式中的公式仅适用于单行,如第一条评论中所述.

但是,如果您只需要突出显示所选内容,您还可以使用 only

Worksheet_SelectionChange
事件和两个变量来保留之前选择的范围。请复制工作表代码模块中您想要突出显示的下一个代码:

Option Explicit

Private prevSelection As Range, col As Long

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 If Not Intersect(Target, Me.UsedRange.Resize(Me.UsedRange.rows.count - 2).Offset(2)) Is Nothing Then
   If prevSelection Is Nothing Then  'first time, when nothing has been selected
      Set prevSelection = Target: col = Target.Interior.Color: Exit Sub
   End If
   prevSelection.Interior.Color = IIf(col <> 0, col, 16777215) 'sometimes in case of multiple selections col becomes zero...
   Set prevSelection = Target   'memorize the selected range for the next selection
   col = Target.Interior.Color  'memorize the selection color, for the next selection
   Target.Interior.Color = RGB(250, 190, 142)
 End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.