【问题标题】:Excel VBA Dynamic filtersExcel VBA 动态过滤器
【发布时间】:2019-01-27 19:08:31
【问题描述】:

我正在尝试根据不同的条件和不同的标准创建动态过滤器。假设用户正在提供一些数据,例如

Sal>100 and sal<1000 and not equal to 500

我能够动态地创建包含所有条件和值的字符串并将其存储在变量中。

示例如下:

Filter_con 具有以下值

Criteria1:=">10", Operator:=xlAnd, Criteria2:="<100000000",Operator:=xlFilterValues

当我尝试执行代码时

Selection.AutoFilter Field:=235, Filter_con

我收到错误:

运行时错误:1004 范围类的 AutoFilter 方法失败。

这里是代码

t_lastrow = Cells(Rows.Count, 1).End(xlUp).Row
Range("A3:XFD" & t_lastrow).Select
If (ActiveSheet.AutoFilterMode And ActiveSheet.FilterMode) Or 
ActiveSheet.FilterMode Then
Selection.ShowAllData
End If
Filter_Con=">10","<100000000"
Filter_numric_data = Split(Replace(Filter_Con, Chr(34), ""), ",")
UBU = UBound(Filter_numric_data)
     Filter_Con = ""
        For i__ = 0 To UBU
           If i__ <> UBU Then
             MsgBox (Filter_numric_data(i__))
            Filter_Con = Filter_Con & " Criteria" & i__ + 1 & ":=" & 
            Filter_numric_data(i__) & ", Operator:=xlAnd,"
           Else
            Filter_Con = Filter_Con & " Criteria" & i__ + 1 & ":=" & 
            Filter_numric_data(i__)
        End If
        Next
       Range("A3:XFD" & t_lastrow).Select
       Selection.AutoFilter Field:=Filter_Field & "," & Filter_Con

【问题讨论】:

  • 什么是选择?
  • 您可以使用问题下方的edit 链接来更改它/添加其他信息。 FWIW我不清楚你的最后评论在问题信息的背景下意味着什么......
  • 如果您想回复 cmets 中的某个人,您需要在他们的姓名前加上 @ - 这会在他们的收件箱中添加一条消息。例如:@satyanarayanavanka。否则,cmet 只会发送到您的收件箱,即提出问题的人。

标签: excel vba


【解决方案1】:

创建一个包含所有要显示的值的字典。通过 xlfiltervalues 使用字典项作为条件 1。

Option Explicit

Sub sdfgh()
    Dim vals As Variant, i As Long, dict As Object

    Set dict = CreateObject("scripting.dictionary")

    With Worksheets("sheet1")

        If .AutoFilterMode Then .AutoFilterMode = False

        vals = .Range(.Cells(2, "IA"), .Cells(.Rows.Count, "IA").End(xlUp)).Value2

        For i = LBound(vals, 1) To UBound(vals, 1)

            Select Case True
                Case vals(i, 1) > 100 And vals(i, 1) < 1000 And vals(i, 1) <> 500
                    'xlFilterValues requires text
                    dict.Item(vals(i, 1)) = CStr(vals(i, 1))
                Case Else
                    'do nothing
            End Select

        Next i

        With .Cells(1, "A").CurrentRegion

            .AutoFilter field:=235, Criteria1:=dict.items, Operator:=xlFilterValues

        End With

    End With
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多