VBA突出显示所选行会导致选择整行

时间:2015-12-21 19:33:24

标签: excel vba excel-vba

我编写了一个突出显示所选行的代码。如果选择更改 - 新选择的行将突出显示,并且上一个选择的格式将返回到初始值。我用

  • 第9行作为高亮格式化示例和
  • 第10行作为未选择行的条件格式的基线。

代码工作正常。但是,当选择单元格时,行会突出显示,所选单元格保持活动状态,但选择整行。有人可以帮我取消选择目标细胞以外的所有东西吗?

here没有任何帮助。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

LastRowA = Range("A" & Rows.Count).End(xlUp).Row

If Target.Cells.Count > 1 Or Target.Cells.Count < 1 Then 'If selected 1 cell
    'Do nothing
Else
    Application.ScreenUpdating = False
    If Target.Row > 10 And Target.Row < LastRowA + 1 Then

        Rows("10:10").Copy 'Restore all rows to custom conditional formatting of row 10
        For tableRow = 11 To LastRowA 
            Rows(tableRow & ":" & tableRow).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        Next tableRow

        Rows("9:9").Copy 'Highlight active row using formating of row #9
        Rows(Target.Row).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

        Application.CutCopyMode = False
        Target.Cells.Activate 'Return Target to initially selected cell
    End If
    Application.ScreenUpdating = True
End If

End Sub

1 个答案:

答案 0 :(得分:3)

试试这个

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim LastRowA As Long
Dim tableRow As Long

LastRowA = Range("A" & Rows.Count).End(xlUp).Row

If Target.Cells.Count > 1 Or Target.Cells.Count < 1 Then 'If selected 1 cell
    'Do nothing
Else
    Application.ScreenUpdating = False
    If Target.Row > 10 And Target.Row < LastRowA + 1 Then

        Rows("10:10").Copy 'Restore all rows to custom conditional formatting of row 10
        For tableRow = 11 To LastRowA
            Rows(tableRow & ":" & tableRow).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        Next tableRow

        Rows("9:9").Copy 'Highlight active row using formating of row #9
        Rows(Target.Row).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

        Application.CutCopyMode = False
        Target.Cells.Activate 'Return Target to initially selected cell
        Application.EnableEvents = False
        Target.Cells.Select
        Application.EnableEvents = True
    End If
    Application.ScreenUpdating = True
End If

End Sub