如何为高亮过滤的行交替编写宏

时间:2017-03-26 15:39:49

标签: excel vba excel-vba

如何在Excel中为此形成结构编写宏以突出显示已过滤的行...先前感谢

enter image description here

3 个答案:

答案 0 :(得分:1)

如果您的号码被分成总是不同数字重复的块,那么您可以使用此VBA代码:

Sub main()
    Dim item As Variant
    Dim startRow As Long
    Dim okHighlight As Boolean

    With Range("A1", Cells(Rows.count, 1).End(xlUp))
        For Each item In GetUniqueValues(.Cells).Items
            If okHighlight Then .Range(.Cells(startRow, 1), .Cells(item, 1)).Interior.ColorIndex = 48
            startRow = item + 1
            okHighlight = Not okHighlight
        Next
    End With
End Sub


Function GetUniqueValues(rng As Range) As Dictionary
    Dim cell As Range
    Dim dict As Dictionary

    Set dict = New Dictionary
    With dict
        For Each cell In rng
            .item(cell.Value) = cell.row - rng.Rows(1).row + 1
        Next
    End With
    Set GetUniqueValues = dict
End Function

使用辅助列

可以实现条件格式化方法

假设:

  • 您的数据位于A列,从第2行开始

  • B栏是免费的

然后:

  • 在辅助列B单元格中编写以下公式:

    = IF(A2<> A1,B1 + 1,0)

  • 使用以下公式将条件格式应用于A列:

    = INT(B2 / 2)= B2 / 2

并选择您想要突出显示单元格的格式

答案 1 :(得分:1)

此处您是朋友,请将y替换为您的工作表名称。

Sheet4

答案 2 :(得分:0)

在众多方法中,有另一种方法:

Option Explicit

Sub colorAltRowGroups()

  With Sheets(1)

    Dim colorCell As Boolean: colorCell = False

    Dim val As String, prvVal As String
    prvVal = .Cells(1, 1).Value

    Dim c As Range
    For Each c In Range("A1", .Cells(Rows.Count, 1).End(xlUp)):
      val = c.Value
      If (val <> prvVal) Then colorCell = Not colorCell
      If colorCell Then c.Interior.Color = vbYellow
      prvVal = val
    Next

  End With

End Sub

编辑:

如果您想为整行着色,可以使用以下代码替换上面代码中的If colorCell语句:

If colorCell Then c.EntireRow.Interior.Color = vbYellow