Trying to Run Make Table Query in Access, from Exc

2019-08-22 06:01发布

问题:

I'm testing the script below.

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

I am getting an error on this line:

Set MyRecordset = MyQueryDef.OpenRecordset

The error reads: Run-time Error '3219' Invalid Operation.

I think one of my references to an object is not being set correctly, but I really don't know what the problem is.

I'm just trying to grab a StartDate and EndDate from 2 cells in Excel and pass both to a Make Table Query in Access. How can I do that?

Thanks!

回答1:

I ended up inputting the dates into two parameters that come from the 2 Action Queries that I'm running. Although I couldn't figure out how to pass in the parameters from cells on a Worksheet, he script below works fine.

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