【问题标题】:Comparing two filtered columns?比较两个过滤列?
【发布时间】:2020-01-18 15:20:52
【问题描述】:

我有一个经过过滤的电子表格,我需要比较两列的值,如果它们在可见的过滤单元格中都相同,则执行宏 a,如果其中任何一个不同,则执行宏 b。

我已经尝试将范围定义为:

Set rng1 = Range("X:X").Cells.SpecialCells(xlCellTypeVisible)

Set rng2 = Range("AU:AU").Cells.SpecialCells(xlCellTypeVisible)

并定义第一个可见范围的值

valE = ActiveSheet.Range("X:X").Cells.SpecialCells(xlCellTypeVisible).Value

valX = ActiveSheet.Range("AU:AU").Cells.SpecialCells(xlCellTypeVisible).Value

我不知道如何编写一个循环遍历指定范围比较下一个可见行。我应该参考什么?

【问题讨论】:

  • 首先,我会将Range 限制为小于整列...
  • 是的,但是宏的目的是用于多页,所以每次都可以有不同数量的记录,我无法预先定义。我对 vba 很陌生,如果我问愚蠢的问题,我很抱歉:P
  • 那你可以find the last cell.
  • FWIW 无参数 Range.Cells 在 99% 的情况下是完全冗余的。
  • 另外 - 一个不连续的范围(假设当你过滤不连续的行是可见的) - 如果我理解你想要做什么,就不能读入这样的数组.

标签: excel vba loops filtering


【解决方案1】:
Sub REName_()

    Dim r1 As Range, _
            r2 As Range

' your code
Set rng1 = Range("X:X").Cells.SpecialCells(xlCellTypeVisible)
Set rng2 = Range("AU:AU").Cells.SpecialCells(xlCellTypeVisible)
'

    If Ranges_Filtered_Compare_Visible(rng1 , rng2 ) Then
        'a
    Else
        'b
    End If

End Sub

Function Ranges_Filtered_Compare_Visible( _
        r1 As Range, _
        r2 As Range) _
        As Boolean

    Dim wb As Workbook, _
            ws As Worksheet

    Set wb = Workbooks.Add
    Set ws = wb.ActiveSheet

    With ws
        r1.Copy .Cells(1, 1)
        r2.Copy .Cells(1, 2)

        If Columns_next_door_compare(.Cells(1, 1)) Then

            Ranges_Filtered_Compare_Visible = True

        End If
    End With

    wb.Close False

End Function

Function Columns_next_door_compare( _
        ceLL As Range) _
        As Boolean

    Dim r As Range
    Set r = ceLL.CurrentRegion.Columns(1)

    Dim bCells_Equal As Boolean
    bCells_Equal = True

    For Each ceLL In r.Cells

    With ceLL
        If .Value <> .Offset(0, 1).Value Then

            bCells_Equal = False

            Exit For

        End If
    End With

    Next

    Columns_next_door_compare = bCells_Equal

End Function

【讨论】:

  • 哇,这实际上完全解决了这个问题,谢谢!我有一个问题,有没有办法在此代码执行后突出显示原始工作表中不匹配的单元格?
【解决方案2】:
Sub Range_Compare_Color( _
    r1 As Range, _
    r2 As Range, _
    lColor As Long)
    ' slowly and solemnly
    ' paint in the first range of a cell that is not in the second

    Dim ceLL As Range

    For Each ceLL In r1

        With ceLL

            If inRange(.Value, r2) = False Then

                .Interior.Color = lColor

            End If
        End With
    Next
End Sub

Function inRange( _
         s As String, _
         r As Range) _
         As Boolean

    Dim found As Range
    Set found = r.Find(s)

    If Not found Is Nothing Then

        inRange = True

    End If
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2015-08-04
    • 1970-01-01
    • 2020-06-17
    • 2019-11-27
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多