简体   繁体   English

可变范围的VBA自动过滤器

[英]VBA Autofilter with variable range

I am trying to make my autofilter range based on the value of variables, but it isn't working. 我正在尝试根据变量的值来设置自动过滤范围,但无法正常工作。 Does anyone have any suggestions? 有没有人有什么建议?

                   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

Your main issue is you're using Range(Cells()) , which isn't how VBA likes things. 您的主要问题是您正在使用Range(Cells()) ,这不是VBA喜欢的方式。 If using a range, you want to do either Range("A1") , or Cells(1,1) . 如果使用范围,则要执行Range("A1")Cells(1,1) If you need to use Range , then you just do Range(Cells(1,1),Cells(1,1)) . 如果需要使用Range ,则只需执行Range(Cells(1,1),Cells(1,1))

So, in your erroring line, change the key to Key:=Cells(z,y) or Range(Cells(z,y),Cells(z,y)) . 因此,在出错的行中,将键更改为Key:=Cells(z,y)Range(Cells(z,y),Cells(z,y))

However, I also highly recommend avoiding using .Select / .Active : 但是,我也强烈建议避免使用.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM