繁体   English   中英

根据列值过滤工作表数据存在于另一工作表中

[英]Filter sheet data based on a column value exists in another sheet

我有一张数据与此类似的工作表

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

我们怎样才能做到

保存在其他表中的值的数组,在我的代码下面是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM