我有两张纸,第一张叫做Enter,第二张叫做结果
我有两个细胞E2和F2。 E2允许用户输入alower bound,F2允许用户输入我需要用来自动过滤结果表中数据的上限。结果表中的D列标题为Number。
我试图开始但不确定如何在两个值之间进行过滤。
Worksheets("Results").Range("D2").AutoFilter Field:=1, Criteria1:= _
">" & Worksheets("Enter").Range("E2").Value, Operator:=xlAnd, Criteria2:="<" & Worksheets("Entry").Range("E3").Value
答案 0 :(得分:4)
我认为您的问题是由于未声明您的范围正确过滤而导致的,因为您的代码只是在查看要过滤的单元格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: 要在条件为空时忽略过滤器,请使用:
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: 我已经重写了很多代码,包括你正在使用表格并包含第二个过滤器,详见评论。我还评论了代码,以帮助您了解它正在做什么以及为什么
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