尝试从Excel中运行在Access中生成表查询

时间:2017-06-14 21:34:08

标签: vba excel-vba access-vba excel

我正在测试下面的脚本。

Sub Update_All()

Dim MyDatabase As DAO.Database
Dim MyQueryDef As DAO.QueryDef
Dim MyRecordset As DAO.Recordset
Dim i As Integer

'Step 2: Identify the database and query

PathOfWorkbook = ThisWorkbook.Path
FullPathOfAccess = PathOfWorkbook & "\TRANSACTIONINFO.accdb"
Set MyDatabase = DBEngine.OpenDatabase(FullPathOfAccess)
Set MyQueryDef = MyDatabase.QueryDefs("TRANSBYMONTH")

With MyQueryDef
.Parameters("[StartDate]") = Worksheets("Date").Range("B9").Value
.Parameters("[EndDate]") = Worksheets("Date").Range("B10").Value
End With

'Step 4: Open the query
Set MyRecordset = MyQueryDef.OpenRecordset

'MyQueryDef.Execute
MyQueryDef.Close

aa.DoCmd.SetWarnings WarningsOn:=True

Set MyDatabase = Nothing
Set MyQueryDef = Nothing

' Shut down reference to Access; clean up
aa.Quit

' Refresh all links to Access
ActiveWorkbook.RefreshAll

End Sub

我在这一行收到错误:

Set MyRecordset = MyQueryDef.OpenRecordset

错误内容为:运行时错误' 3219'操作无效。

我认为我对某个对象的引用没有正确设置,但我真的不知道问题是什么。

enter image description here

enter image description here

我只是试图从Excel中的2个单元格中获取StartDate和EndDate,并将它们传递给Access中的Make Table Query。我怎么能这样做?

谢谢!

1 个答案:

答案 0 :(得分:0)

我最终将日期输入到两个参数中,这些参数来自我正在运行的2个动作查询。虽然我无法弄清楚如何从工作表上的单元格传递参数,但下面的脚本工作正常。

Sub Update_All()

MsgBox ("It may take several minutes for all Queries to finish.  Please wait for the 'Done' message to confirm that the task is complete.")

    Dim strDatabasePath As String
    Dim oApp As Access.Application
    Dim PathOfworkbook As String

    PathOfworkbook = ThisWorkbook.Path

    strDatabasePath = PathOfworkbook & "\TRANSACTIONS.accdb"

    Set oApp = CreateObject("Access.Application")
    oApp.Visible = False

    oApp.OpenCurrentDatabase strDatabasePath

    With oApp
        Application.DisplayAlerts = False
        '.OpenCurrentDatabase strDatabasePath

        ' Run first Action Query
        .DoCmd.OpenQuery "KEY"

        ' Run second Action Query
        .DoCmd.OpenQuery "TRBYMONTH"

        .Quit
    End With

    Set appAccess = Nothing

    MsgBox ("Done!  All Access Queries have been updated!!")

End Sub