自动过滤后应用高级过滤器

时间:2014-04-10 22:41:11

标签: excel vba excel-vba filter

我想做两次连续过滤;第一个在我使用自动过滤器的日期和生成的结果我想做进行过滤(因为我记住了OR)。 所以我首先要做的是将范围变量设置为未过滤范围。

Set rng = Range(ws.Cells(1, 1), ws.Cells(rowNos, colNos))

然后使用自动过滤器I过滤给定日期。

rng.AutoFilter Field:=1, Criteria1:=">" & lDate

由于现在会隐藏一些行,而我想应用高级过滤器,我使用了特殊单元

rng.SpecialCells(xlCellTypeVisible).AdvancedFilter Action:=xlFilterCopy, _
    CriteriaRange:=crt, CopyToRange:=thisWB.Worksheets("Sheet3").Range("A1"), _
    Unique:=False

但是我在最后一步中遇到错误"该命令至少需要两行数据。 。 "我确保至少有100行符合标准,这意味着错误不是因为缺少行。

请帮助我解决问题。此外,如果我能够完成任务的另一种方式,我将很乐意改变我的代码。我尝试做的是针对特定日期过滤表格,然后再次过滤两列上的值(通常使用高级过滤器)。

1 个答案:

答案 0 :(得分:1)

似乎.AdvancedFilter不适用于非连续范围。下面的代码有点像kludge-y,但是工作了一个小例子我拉在一起我要返回的观察结果是> 2014年4月1日,Foo = Yes,Bar = 7.我的数据表中只包含一行符合所有条件的行。

setup

Option Explicit
Sub FilterTwice()

Dim DataSheet As Worksheet, TargetSheet As Worksheet, _
    ControlSheet As Worksheet, TempSheet As Worksheet
Dim DataRng As Range, ControlRng As Range, _
    TempRng As Range
Dim lDate As Date
Dim LastRow As Long, LastCol As Long

'assign sheets for easy reference
Set DataSheet = ThisWorkbook.Worksheets("Sheet1")
Set ControlSheet = ThisWorkbook.Worksheets("Sheet2")
Set TargetSheet = ThisWorkbook.Worksheets("Sheet3")

'clear any previously-set filters
Call ClearAllFilters(DataSheet)

'assign data range
LastRow = DataSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastCol = DataSheet.Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Set DataRng = Range(DataSheet.Cells(1, 1), DataSheet.Cells(LastRow, LastCol))

'assign a control (or critieria) range for the advanced filter
Set ControlRng = Range(ControlSheet.Cells(1, 1), ControlSheet.Cells(2, 2))

'apply date filter
lDate = "4/1/2014"
With DataRng
    .AutoFilter Field:=1, Criteria1:=">" & lDate
End With

'add a temporary sheet and copy the visible cells to create a continuous range
Set TempSheet = Worksheets.Add
DataRng.SpecialCells(xlCellTypeVisible).Copy
TempSheet.Range("A1").PasteSpecial Paste:=xlPasteAll

'assign temp range
LastRow = TempSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastCol = TempSheet.Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Set TempRng = Range(TempSheet.Cells(1, 1), TempSheet.Cells(LastRow, LastCol))

'apply advanced filter to temp range and get obs where foo = yes and bar = 7
With TempRng
    .AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=ControlRng, _
        CopyToRange:=TargetSheet.Range("A1"), Unique:=False
End With

'remove the temp sheet and clear filters on the data sheet
Application.DisplayAlerts = False
TempSheet.Delete
Application.DisplayAlerts = True
DataSheet.AutoFilterMode = False

End Sub

Sub ClearAllFilters(cafSheet As Worksheet)
    With cafSheet
        .AutoFilterMode = False
        If .FilterMode = True Then
            .ShowAllData
        End If
    End With
End Sub