如何使用Excel VBA中的用户input框数据复制多个filter

在这里输入图像描述

我想通过input框从用户获得多个input并过滤表格。 只有一列被过滤。 然后将整个行数据复制到另一个工作表。 我使用下面的代码。 问题是可以用来过滤1个国家。

F列中有很多国家。我需要在input框中input2个或更多的国家。 然后复制并粘贴。 我想添加Loop。 但我不知道如何。 帮我

Private Sub CommandButton1_Click() Dim str1 As Variant Dim Tbl As ListObject Dim FiltRng As Range Dim RngArea As Range Set Tbl = Sheet1.ListObjects("DataTable") str1 = Application.InputBox("Select the Country Code") If str1 = False Then MsgBox "Please select one Country", , "Input" Exit Sub Else Tbl.Range.AutoFilter Field:=6, Criteria1:=str1 For Each RngArea In Tbl.Range.SpecialCells(xlCellTypeVisible).Rows If RngArea.Row > 1 Then If Not FiltRng Is Nothing Then Set FiltRng = Application.Union(FiltRng, RngArea) Else Set FiltRng = RngArea End If End If Next RngArea If Not FiltRng Is Nothing Then FiltRng.Copy Sheets("Sheet2").Range("A2") End If End If Sheet1.ListObjects("DataTable").Range.AutoFilter Field:=6 End Sub 

你可以在InputBox中循环读取。 尝试下面的代码。

 Sub Macro3() Dim arr() As String Dim size As Long size = 1 Do str1 = Application.InputBox("Select the Country Code") ReDim Preserve arr(size) arr(size) = str1 size = size + 1 Loop While (str1 <> vbNullString) And (str1 <> False) ActiveSheet.Range("$A$1:$F$5").AutoFilter Field:=6, Criteria1:=arr, Operator:=xlFilterValues End Sub 

为什么不简单地制作数据透视表,将数据透视表放在另一张表中,并添加一个切片器,以便用户可以select他们想要的国家? 没有必要的VBA。

使用以下两个条件来筛选表格并将过滤的数据复制到sheet2 。 您可以根据需要添加更多标准。

 Sub Filter2Criteria() Dim str1, str2 As Variant Dim Tbl As ListObject Dim FiltRng As Range Dim RngArea As Range Set Tbl = Sheet1.ListObjects("DataTable") str1 = Application.InputBox("Select the Country Code") str2 = Application.InputBox("Select the Country Code") If str1 = False Then MsgBox "Please select first Country", , "Input" Exit Sub ElseIf str2 = False Then MsgBox "Please select second Country", , "Input" Exit Sub End If Tbl.Range.AutoFilter Field:=6, Criteria1:=str1, Operator:=xlOr, Criteria2:=str2 Set FiltRng = Tbl.Range.SpecialCells(xlCellTypeVisible) FiltRng.Copy Sheets("Sheet2").Range("A2") End Sub