使用vba过滤两个值之间的数据

我有两张表,第一个叫做Enter,第二个叫做Results

我有两个单元格E2和F2。 E2允许用户input下限,F2允许用户input上限,我需要使用自动筛选结果表中的数据。 结果表中的D列标题为Number。

我试图做一个开始,但不知道如何过滤两个值之间。

Worksheets("Results").Range("D2").AutoFilter Field:=1, Criteria1:= _ ">" & Worksheets("Enter").Range("E2").Value, Operator:=xlAnd, Criteria2:="<" & Worksheets("Entry").Range("E3").Value 

我认为你的问题是由于没有声明你的范围过滤正确,因为在你的代码中,你只是在看D2单元格进行过滤

尝试

 Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("Results") With ws .Range("$D$2:$D$" & .Range("D" & Rows.Count).End(xlUp).Row).AutoFilter field:=1, _ Criteria1:=">" & Worksheets("Enter").Range("E2").Value, _ Operator:=xlAnd, _ Criteria2:="<" & Worksheets("Entry").Range("E3").Value End With 

更新1:如果条件为空,则忽略filter使用:

 Dim ws As Worksheet Dim Enter As Worksheet Dim Entry As Worksheet Set ws = ThisWorkbook.Sheets("Results") Set Enter = ThisWorkbook.Sheets("Enter") Set Entry = ThisWorkbook.Sheets("Entry") If Not IsEmpty(Enter.Range("E2")) And Not IsEmpty(Entry.Range("E3")) Then With ws .Range("$D$2:$D$" & .Range("D" & Rows.Count).End(xlUp).Row).AutoFilter Field:=1, _ Criteria1:=">" & Enter.Range("E2").value, _ Operator:=xlAnd, _ Criteria2:="<" & Entry.Range("E3").value End With End If 

更新2:我已经重写了很多的代码,包括你使用的表格,并包括第二个filter详细的评论。 我也评论了代码,以帮助您了解它在做什么和为什么

 Dim ws As Worksheet: Dim Enter As Worksheet: Dim Entry As Worksheet Dim NoRow As Integer Dim c ' Turn off screen updating (code runs faster) Application.ScreenUpdating = False ' Set worksheets to variables Set ws = ThisWorkbook.Sheets("Results") Set Enter = ThisWorkbook.Sheets("Enter") Set Entry = ThisWorkbook.Sheets("Entry") With ws.ListObjects("Results") ' Reset the filter for the Results table .AutoFilter.ShowAllData ' Test to see if between criteria is set if not the results table will stay unfiltered If Not IsEmpty(Enter.Range("E2")) And Not IsEmpty(Entry.Range("E3")) Then ' Find how many Locations are set to show. If none macro will exit the sub With Entry.ListObjects("Location") .Range.AutoFilter field:=.ListColumns("Show").Index, _ Criteria1:="Show" ' Error handling On Error Resume Next NoRow = .DataBodyRange.SpecialCells(xlCellTypeVisible).Rows.Count On Error GoTo 0 End With ' Filter 'Show' Locations If NoRow = 1 Then .Range.AutoFilter field:=.ListColumns("Location").Index, _ Criteria1:=Entry.ListObjects("Location") _ .DataBodyRange.SpecialCells(xlCellTypeVisible).Cells(1, 1) ' Handle if all Locations are hidden ElseIf NoRow = 0 Then MsgBox "All Locations are hidden" GoTo CleanUp End If ' Filter Area with between criteria .Range.AutoFilter field:=.ListColumns("Area").Index, _ Criteria1:=">" & Enter.Range("E2").Value, _ Operator:=xlAnd, _ Criteria2:="<" & Entry.Range("E3").Value End If End With CleanUp: ' Reset Location table to show all Locations again Entry.ListObjects("Location").AutoFilter.ShowAllData Application.ScreenUpdating = True