VBA自动过滤器,可变范围

时间:2016-07-08 17:12:36

标签: excel vba

我正在尝试根据变量的值制作自动过滤器范围,但它不起作用。有没有人有什么建议?

                   Dim y, z As Integer
                   y = 5
                   z = 3

                    rows(z).Select
                    Selection.AutoFilter
                    ActiveWorkbook.Worksheets("Active Worksheet").AutoFilter.Sort.SortFields.Clear
                    **ActiveWorkbook.Worksheets("Active Worksheet").AutoFilter.Sort.SortFields.Add _
                    Key:=Range(Cells(z, y)), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
                    :=xlSortNormal**
                    With ActiveWorkbook.Worksheets("Active Worksheet").AutoFilter.Sort
                        .Header = xlYes
                        .MatchCase = False
                        .Orientation = xlTopToBottom
                        .SortMethod = xlPinYin
                        .Apply
                    End With

1 个答案:

答案 0 :(得分:2)

你的主要问题是你正在使用Range(Cells()),这不是VBA喜欢的东西。如果使用范围,您可以执行Range("A1")Cells(1,1)。如果您需要使用Range,那么您只需执行Range(Cells(1,1),Cells(1,1))

因此,在错误行中,将密钥更改为Key:=Cells(z,y)Range(Cells(z,y),Cells(z,y))

但是,我也highly recommend avoiding using .Select/.Active

Sub whatever()
Dim y As Integer, z As Integer
Dim mainWB  As Workbook
Dim activeWS As Worksheet

Set mainWB = ActiveWorkbook
Set activeWS = mainWB.Worksheets("Active Worksheet")

y = 5
z = 3

With activeWS
    .Rows(z).AutoFilter
    .AutoFilter.Sort.SortFields.Clear
    .AutoFilter.Sort.SortFields.Add Key:=.Cells(z, y), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With .AutoFilter.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End With
End Sub