Autofilter Excel with VBA

こ雲淡風輕ζ 提交于 2020-01-17 06:16:08

问题


I would like to open Excel from Access and apply filters to a sheet. Below is my code:

Dim s as String
Set oApp = CreateObject("Excel.Application")
oApp.Wworkbooks.Open FileName:="dudel.xlsm"
oApp.Visible = True
s = "AB"
With oApp
        .Rows("2:2").Select
        .Selection.AutoFilter
        .ActiveSheet.Range("$A$2:$D$9000").AutoFilter Field:=3, Criteria1:= _ 
             Array(s, "E", "="), Operator:=xlFilterValues
        .Range("A3").Select 
End With

When I ran the code, I got this error:

runt time error 1004 Autofilter methond of range class failed

Can anyone see why?


回答1:


Try this one. I've commented code in details, but if you have some questions - ask:)

Sub test()
    Dim s As String
    Dim oApp As Object
    Dim wb As Object
    Dim ws As Object


    Set oApp = CreateObject("Excel.Application")
    oApp.Visible = True

    'tries to open workbook
    On Error Resume Next
    'change file path to the correct one
    Set wb = oApp.workbooks.Open(FileName:="C:\dudel.xlsm")
    On Error GoTo 0

    'if workbook succesfully opened, continue code
    If Not wb Is Nothing Then
        'specify worksheet name
        Set ws = wb.Worksheets("Sheet1")
        s = "AB"
        With ws
            'disable all previous filters
            .AutoFilterMode=False
            'apply new filter
            .Range("$A$2:$D$9000").AutoFilter Field:=3, Criteria1:=Array(s, "E"), Operator:=7
        End With

        'close workbook with saving changes
        wb.Close SaveChanges:=True
        Set wb = Nothing
    End If

    'close application object
    oApp.Quit
    Set oApp = Nothing
End Sub

and also one more thing: change Operator:=xlFilterValues to Operator:=7 (access doesn't know about excel constanst until you add reference to the excel library in access)



来源:https://stackoverflow.com/questions/21730446/autofilter-excel-with-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!