动态标准 - 过滤Excel VBA

时间:2015-05-14 14:16:14

标签: excel vba excel-vba

我需要按照相同的标准进行过滤,但标准的值在我收到的数据中并不总是相同,因此它们必须是动态的。

例如。

将crit1变为String crit1 =?

那样:

Selection.AutoFilter Field:= 4,Criteria1:= crit1

这是我的代码

enter code herexDim TaskType, Status, Elapse As Long
Dim Total, Completed As Variant
Total = Array("COMPLETED", "ERROR", "KILLED")
Completed = Array("COMPLETED")
TaskType = WorksheetFunction.Match("tasktypeid", Rows("1:1"), 0)
Status = WorksheetFunction.Match("status", Rows("1:1"), 0)
Elapse = WorksheetFunction.Match("elapse", Rows("1:1"), 0)
'Use Filter Criteria
'100 Total
With Sheets("Raw_Data")
Set rnData = .UsedRange
With rnData
.AutoFilter field:=TaskType, Criteria1:="100"
.AutoFilter field:=Status, Criteria1:=Total, Operator:=xlFilterValues
.Select
        For Each rngarea In .SpecialCells(xlCellTypeVisible).Areas
        lcount = lcount + rngarea.Rows.Count
        Next
        a = lcount - 1
   End With
      End With
'100 Completed
    With Sheets("Data")
    Set rnData = .UsedRange
    With rnData
    .AutoFilter field:=TaskType, Criteria1:="100"
    .AutoFilter field:=Status, Criteria1:=Completed, Operator:=xlFilterValues
    .Select
            For Each rngarea In .SpecialCells(xlCellTypeVisible).Areas
            lcount1 = lcount1 + rngarea.Rows.Count
            Next
            b = lcount1 - 1
       End With
          End With

'101 Total
    With Sheets("Raw_Data")
    Set rnData = .UsedRange
    With rnData
    .AutoFilter field:=TaskType, Criteria1:="101"
    .AutoFilter field:=Status, Criteria1:=Total, Operator:=xlFilterValues
    .Select
            For Each rngarea In .SpecialCells(xlCellTypeVisible).Areas
            lcount2 = lcount2 + rngarea.Rows.Count
            Next
            c = lcount2 - 1
       End With
          End With
'101 Completed
    With Sheets("Data")
    Set rnData = .UsedRange
    With rnData
    .AutoFilter field:=TaskType, Criteria1:="101"
    .AutoFilter field:=Status, Criteria1:=Completed, Operator:=xlFilterValues
    .Select
            For Each rngarea In .SpecialCells(xlCellTypeVisible).Areas
            lcount3 = lcount3 + rngarea.Rows.Count
            Next
            d = lcount3 - 1
       End With
          End With

在上面的代码中,我已经静态计算了criteria1:= 100,101,但它应该采用过滤器中存在的动态值。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

例如, 使用我的宏录制器过滤列“I”包含“a”的项目,我会得到这种代码。

Sub Macro5()
'
' Macro5 Macro
'

'
    Columns("I:I").Select
    Selection.AutoFilter
    ActiveSheet.Range("$I$1:$I$7").AutoFilter Field:=1, Criteria1:="=*a*", _
                                              Operator:=xlAnd
End Sub

现在我看到代码如何使用通配符,我现在可以编辑代码以使用通配符和变量。 我的新代码看起来像这样。

Sub FilterForA()
    Dim s As String
    s = "a"
    Columns("I:I").AutoFilter Field:=1, Criteria1:="=*" & s & "*"
End Sub