创建一个用于自动过滤VBA的数组

时间:2016-02-19 02:55:44

标签: arrays excel vba filter autofilter

我非常感谢以下任何帮助:

我通过彩色文本从“myData”范围获取用户输入以用于自动过滤更大范围 - 所以这里是用于查找红色文本单元格的地址及其值的代码:

Set rRng = Sheet1.Range("myData")

For Each rCell In rRng.Cells
    If rCell.Font.ColorIndex = 3 Then 
    Debug.Print rCell.Address, rCell.Value
    Counter = Counter + 1
    End If
Next rCell

我必须将这些发现放入一个数组中并使用它们来过滤选择(此时选择是在“myTable”中进行选择);当然,调查结果确实告诉我们哪些字段和使用的值:如果调查结果是:c18“x”,d19“y”和d21“z”,则自动过滤器必须说:

With ActiveSheet
    .AutoFilterMode = False
        With .Range("myTable")
            .AutoFilter
            .AutoFilter Field:=3, Criteria1:="x"
            .AutoFilter Field:=4, Criteria1:="y", Operator:=xlOr, Criteria2:="z"
        End With
        Selection.Offset(1, 0).Resize(Selection.Rows.Count - 1).Select
        Selection.Font.ColorIndex = 3
End With

这两个代码都可以正常工作,但当然我必须编写代码来自动完成整个过程。 谢谢。

1 个答案:

答案 0 :(得分:0)

可能有更好更快的方法,但我可以使用以下代码解决它:

我通过以下代码将标准读入数组:

Set rRng = Sheet1.Range("myData")

For Each rCell In rRng.Cells

    If rCell.Font.ColorIndex = 3 Then '3 = Red

        Counter = Counter + 1

        myAddress(Counter) = rCell.Column - 1
        myValues(Counter) = rCell.Value

        Debug.Print rCell.Address, rCell.Value
        Debug.Print myAddress(Counter), myValues(Counter)

    End If

Next rCell

ReDim Preserve myAddress(Counter + 1)
ReDim Preserve myValues(Counter + 1)

然后我能够在自动过滤中使用数组:

Range("myFirst").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Set myTable = Selection

With ActiveSheet
    .AutoFilterMode = False
        With .Range("myTable")
            .AutoFilter

            For i = 1 To Counter
                .AutoFilter Field:=myAddress(i), Criteria1:=myValues, Operator:=xlFilterValues
            Next i

'             结束             Selection.Offset(1,0).Resize(Selection.Rows.Count - 1).Select             Selection.Font.ColorIndex = 3     

结束