选择与数组中的每个项匹配的行

时间:2013-10-02 17:49:49

标签: arrays excel excel-vba vba

在Excel file1中,我有一个非常大的表,同一列中的每一行都有数字(让我们说col F)。 在Excel file2中,我的数字也在一列中(比如col A)。

问:我如何选择file2中包含来自file1 col A的数字的所有行。

我找到了如何在file2中选择包含来自file1的一个字符串的行...但是字符串数组对我来说有点棘手,而file1中的数组非常大。

Sub SelectManyRows()
Dim CatchPhrase As String
Dim WholeRange As String
Dim AnyCell As Object
Dim RowsToSelect As String

CatchPhrase = "10044" // <- here should be array from file1 col A
'first undo any current highlighting
Selection.SpecialCells(xlCellTypeLastCell).Select
WholeRange = "A1:" & ActiveCell.Address
Range(WholeRange).Select
On Error Resume Next ' ignore errors
For Each AnyCell In Selection
    If InStr(UCase$(AnyCell.Text), UCase$(CatchPhrase)) Then
        If RowsToSelect <> "" Then
            RowsToSelect = RowsToSelect & "," ' add group separator
        End If
        RowsToSelect = RowsToSelect & Trim$(Str$(AnyCell.Row)) & ":" & Trim$(Str$(AnyCell.Row))
    End If
Next
On Error GoTo 0 ' clear error 'trap'
Range(RowsToSelect).Select
End Sub

2 个答案:

答案 0 :(得分:2)

以下想法是试图避免循环,这通常是低效的。相反,我使用AdvancedFilter假设它可能与你拥有的数据集有关。

该代码适用于位于不同工作表(File1和File2)中的以下数据集。您需要根据需要将其更改为与工作簿一起使用。

enter image description here

Sub qTest()

    Sheets("File1").Activate
    Dim sRNG As Range
    Dim aRNG As Range

    Set sRNG = Sheets("File2").Range("S1", Sheets("File2").Range("S1").End(xlDown))
    Set aRNG = Sheets("File1").Range("A1", Sheets("File1").Range("a1").End(xlDown))

    aRNG.AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:=sRNG, Unique:=False

    Dim aADD As String
    aADD = aRNG.SpecialCells(xlCellTypeVisible).Address

    aRNG.Parent.ShowAllData

    Range(aADD).Select

End Sub

答案 1 :(得分:1)

可以使用类似于此的东西。 Select is avoided,但要实际选择您要查找的行。此外,这会动态地将相同的数字添加到最后选择的范围。

Dim cl As Variant
Dim first_range As Boolean: first_range = True
Dim colF_range As Range, selected_range As Range


'colF_range is the list in File 2
Set colF_range = Workbooks("File2").Worksheets("Your_Worksheet") _
.Range("F:F")

'Go through each cell in the File 2 list
For Each cl In colF_range
  'Look if that cell's value matches something
  'in File 1 column A
  If Not Workbooks("File1").Worksheets("Your_Worksheet") _
  .Range("A:A").Find(cl.Value) Is Nothing Then
    'If so, select that row in File 2
    If first_range Then
      Set selected_range = cl.EntireRow
      first_range = False
    Else
      Set selected_range = Application.Union _
      (cl.EntireRow, selected_range)
    End If
  End If
Next