2014-02-12 271 views
0

我想從Access打開Excel並將篩選器應用於工作表。 下面是我的代碼:使用VBA自動篩選Excel

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 

當我運行的代碼,我得到這個錯誤:

runt time error 1004 Autofilter methond of range class failed

任何人都可以看到,爲什麼?

回答

1

試試這個。我評論了詳細的代碼,但如果你有一些問題 - 問:)

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 

,也一件事:改變Operator:=xlFilterValuesOperator:=7(訪問不知道有關Excel constanst直到您添加參考excel庫訪問)

+0

即時對不起仍然給出相同的錯誤 – Xarxas

+0

是您的工作表在Excel中保護?我檢查了 –

+0

。沒有保護 – Xarxas