基于列值的筛选表数据存在于另一个工作表中

时间:2018-03-14 06:09:24

标签: excel vba excel-vba

我有一张包含与此相似的数据

Users  Role
-----------
Name1   a
Name2   b
Name3   c
Name4   d
Name5   e
Name6   f
Name7   g

另一张表

Users Req
------
Name4
Name6
Name7

因此,应根据第二张表中存在的列值过滤工作表数据。因此,在过滤后,第一张纸看起来像这样。

Users   Role
-------------
Name4    d
Name6    f
Name7    g

我们怎样才能达到这样的目标

1 个答案:

答案 0 :(得分:4)

将值保存在数组的其他工作表中,在我的代码FilterArr下方,然后您可以AutoFilter使用Criteria1:=FilterArr根据此数组中的值Option Explicit Sub FilterAccordingtoValuesInOtherSheet() Dim Sht1 As Worksheet, sht2 As Worksheet Dim FilterArr As Variant Dim LastRow As Long Set Sht1 = ThisWorkbook.Sheets("Sheet1") ' modify to your sheet's name where you have the data you want to filer Set sht2 = ThisWorkbook.Sheets("Sheet2") ' modify to your sheet's name where you have values you want to use for the filter With sht2 LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last row with data in column A FilterArr = Application.Transpose(.Range("A2:A" & LastRow).Value2) ' get the values from the second sheet to an array End With With Sht1 LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last row with data in column A ' set the Auto-Filter by column A, to the values in the array .Range("A1:B" & LastRow).AutoFilter Field:=1, Criteria1:=FilterArr, Operator:=xlFilterValues End With End Sub 。 / p>

以下代码中的更多解释为注释:

<强> 代码

https://staff.tumblr.com/rss