【问题标题】:Using Autofilter in Function in vba在 vba 的函数中使用自动过滤器
【发布时间】:2015-03-28 14:57:53
【问题描述】:

下面的函数抛出错误424 Object Required

我想在 Worksheets asformula 中使用它。

上传的报告选项卡中提供数据。第 7 行是标题行。

Function Bookings(Start_date As Date, End_date As Date) As Long
    On Error GoTo Protection
    Dim l_row As Long
    Dim rngRow, resultRng, filterRng As Range
    Bookings = 0
    l_row = Worksheets("Uploaded Report").Cells(Rows.Count, 1).End(xlUp).Row

    Worksheets("Uploaded Report").AutoFilterMode = False

    Set filterRng = Worksheets("Uploaded Report").Range("A7:E" & l_row)
    filterRng.AutoFilter field:=1, Criteria1:="GC Hi Top", VisibleDropDown:=True
    'Worksheets("Uploaded Report").Range("A7:E" & l_row).AutoFilter Field:=3, Criteria1:=">=" & Format(Start_date, "mm/dd/yyyy"), Operator:=xlAnd, Criteria2:="<=" & Format(End_date, "mm/dd/yyyy")
    Worksheets("Uploaded Report").Activate
    Set resultRng = filterRng.AutoFilter.Range.SpecialCells(xlCellTypeVisible)

    For Each rngRow In resultRng
        If rngRow.Row = 7 Then
           GoTo NextIteration
        End If
        If Len(Worksheets("Uploaded Report").Range("A" & rngRow.Row).Value) > 0 Then
            If rngRow.Row > 1 And rngRow.Column = 3 Then
                Bookings = Bookings + 1
            End If
        End If

下一次迭代: 下一个 rngRow

保护: MsgBox Err.Number & Err.Description

End Function

【问题讨论】:

  • 错误发生在哪一行?要找出答案,您可以注释掉On Error GoTo Protection 这一行。

标签: excel vba


【解决方案1】:

如何摆脱错误

在测试您的代码时,以下行引发了错误:
Set resultRng = filterRng.AutoFilter.Range.SpecialCells(xlCellTypeVisible)

将该行更改为:
Set resultRng = filterRng.SpecialCells(xlCellTypeVisible)


其他事情

  1. 我认为你错误地声明了变量。

    Dim rngRow, resultRng, filterRng As Range
    改为
    Dim rngRow As Range, resultRng As Range, filterRng As Range

  2. l_row 的行中,您缺少Rows.count 的父级
    l_row = Worksheets("Uploaded Report").Cells(Rows.Count, 1).End(xlUp).Row
    改为
    l_row = Worksheets("Uploaded Report").Cells(Worksheets("Uploaded Report").Rows.Count, 1).End(xlUp).Row
    或使用With...End With 声明。

  3. 您确定要在函数中使用错误处理程序吗?没有它,它只会在单元格中显示 excel 错误,没有 MsgBox,这对于无知的用户来说是无用和可怕的。如果您选择保留错误处理程序,请在Protection: 标签之前添加一行Exit Function

  4. 为了提高效率并摆脱多余的If...End If 语句,您可以将 resultRng 设置为
    Set resultRng = filterRng.Columns(3).SpecialCells(xlCellTypeVisible)
    这样,您只会遍历“C”列。

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 2021-11-11
    相关资源
    最近更新 更多