【问题标题】:How to group rows that match one of two conditions?如何对匹配两个条件之一的行进行分组?
【发布时间】:2026-01-07 14:30:01
【问题描述】:

我正在尝试编写一个宏来对填充有两种颜色(白色/RGB(255,255,255) 或淡黄色/RBG(255,255,238))之一的行进行分组。但是当我运行我的宏时,它只会对淡黄色的行进行分组。

修正代码(感谢@Vityata):

Option Explicit

Sub RowGrouper()
Dim rng As Range
Dim lastRow As Long
lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row

For Each rng In Range(Cells(10, 1), Cells(lastRow, 1)).Cells
    If rng.Interior.Color = RGB(255, 255, 255) Or rng.Interior.Color = RGB(255, 255, 238) Then
        rng.Rows.Group
    End If
Next

End Sub

最终结果应该是这样的:

感谢您能给我的任何帮助。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    从这里:

    rng.Interior.ColorIndex = rng.Interior.Color = RGB(255, 255, 255)
    

    这样写:

    rng.Interior.Color = RGB(255, 255, 255)
    

    【讨论】:

    • 哇。我很尴尬,我没有看到。那里完全是隧道式的。非常感谢!
    • @CATSandCATSandCATS - 没什么好尴尬的。很高兴我能帮忙:)
    • 想想我只是完全重写了解决方案,哈! X(
    【解决方案2】:

    试一试 - 我发现在分组之前先概述整个范围更容易。

    我看到 Vityata 找到了错字,但我必须发布我的解决方案! :)

    Option Explicit
    
    Sub RowGrouper()
    
        Dim i As Long, j As Long, lastRow As Long
    
        lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
    
        For i = 10 To lastRow
            For j = i To lastRow
                If Cells(j, 1).Interior.Color <> RGB(255, 255, 255) And Cells(j, 1).Interior.Color <> RGB(255, 255, 238) Then
                    If j <> i Then
                        Rows(i & ":" & j - 1).Rows.Group
                        i = j
                        Exit For
                    Else
                        i = i + 1
                    End If
                End If
            Next j
        Next
    
    End Sub
    

    【讨论】:

    • 我喜欢它。这是一个比我正在做的更优雅的解决方案。非常感谢您花时间帮助我!
    最近更新 更多