簡體   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