在vba中使用函数中的自动过滤器

时间:2015-03-28 03:20:59

标签: excel-vba vba excel

以下函数抛出错误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

NextIteration:         下一个rngRow

保护:         MsgBox Err.Number&amp; Err.Description

End Function

1 个答案:

答案 0 :(得分:0)

如何摆脱错误

在测试代码时,错误是由以下行提出的:
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,这对于无能的用户来说是无用的和可怕的。如果您选择保留错误处理程序,请在<{strong> Exit Function标签之前添加一行Protection:

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