1

我在 A 列和 B 列中有 2 列孩子的姓名。它们代表一起工作的成对的孩子。

我想过滤“鲍勃”与任何其他孩子一起工作的所有行。因此,我想过滤在 A 列或 B 列中显示 1 个条件(Bob)的所有行。

我想将这些行或成对的孩子放入一个数组中。我该怎么做呢?

4

2 回答 2

3

I haven't seen Doug's answer on Union of Ranges. But here is an example. This uses Autofilter instead of looping through ranges. I have commented the code so you should not have problem understanding it.

CODE

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range, rngA As Range, rngB As Range
    Dim Lrow As Long

    Set ws = Sheets("Sheet1")

    With ws
        '~~> Get last row of Col A
        Lrow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Identify the range
        Set rng = .Range("A1:B" & Lrow)

        .AutoFilterMode = False

        '~~> Identify the range in Col A Which has BOB
        With rng
            .AutoFilter Field:=1, Criteria1:="Bob"
            Set rngA = .Offset(1, 0).SpecialCells(xlCellTypeVisible)
        End With

        .AutoFilterMode = False

        '~~> Identify the range in Col B Which has BOB
        With rng
            .AutoFilter Field:=2, Criteria1:="Bob"
            Set rngB = .Offset(1, 0).SpecialCells(xlCellTypeVisible)
        End With

        .AutoFilterMode = False

        '~~> Hide All except the Header row
        rng.Offset(1, 0).EntireRow.Hidden = True
        '~~> Unhide the rows which have Bob
        Union(rngA, rngB).EntireRow.Hidden = False
    End With
End Sub

SCREENSHOT

enter image description here

于 2012-08-18T06:54:49.540 回答
1

试试下面的代码。它创建一个便签本表,复制任一列中包含 Bob 的任何行,从结果中创建一个数组,然后删除便签本。

Sub GetBobRows()
    Dim src As Worksheet
    Dim tgt As Worksheet
    Dim rng As Range
    Dim cell As Range
    Dim lastRow As Long
    Dim bobCount As Long
    Dim bobRow As Long

    Set src = ActiveSheet
    Sheets.Add
    ActiveSheet.Name = "Scratchpad"
    Set tgt = ActiveSheet

    ' assumes two columns with Bob data are A and B and start in row 1
    ' of the activesheet
    lastRow = src.Range("A" & src.Rows.Count).End(xlUp).Row

    Set rng = src.Range("A1:A" & lastRow)
    bobCount = 1

    For Each cell In rng
        If cell.Value = "Bob" Or cell.Offset(, 1).Value = "Bob" Then
            bobRow = cell.Row
            tgt.Range("A" & bobCount & ":B" & bobCount).Value = _
                src.Range("A" & bobRow & ":B" & bobRow).Value
            bobCount = bobCount + 1
        End If
    Next
    Call CreateBobArray(tgt)
    DeleteScratchpad
End Sub

Sub CreateBobArray(tgt As Worksheet)
    Dim vaBobs As Variant
    Dim lRow As Long

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

    'Read the data from the scratch pad into the bob array
    vaBobs = tgt.Range("A1:B" & lRow).Value
End Sub

Sub DeleteScratchpad()
    Application.DisplayAlerts = False
        Sheets("Scratchpad").Delete
    Application.DisplayAlerts = True
End Sub
于 2012-08-18T02:21:57.583 回答