Home » excel » vba – run access macro within excel

vba – run access macro within excel

Posted by: admin April 23, 2020 Leave a comment

Questions:

I want within excel vba to run an access macro and also copy an access query.
When I run the code below, I get an runtime error 3001 on line cn.DoCmd.RunMacro “runCopyqueryVragenlijsten”

'~~> Select access file Database Questionmark.mdb
Set cn = CreateObject("adodb.connection")
Set rs = CreateObject("adodb.recordset")
cn.Open "provider=microsoft.jet.oledb.4.0;data source=D:\Data\Geschiktheidstesten en OPQ-rapport NMBS competenties\Analyse\Database Questionmark.mdb"

'~~> Run access macro
cn.DoCmd.RunMacro "runCopyqueryVragenlijsten"

'~~> Select access query to copy
rs.Open "select * from Copyquery_Vragenlijsten", cn

'~~> paste access query in sheet vragenlijst
Worksheets("vragenlijst").Range("a2").CopyFromRecordset rs

'~~> Close access file and put cursor on cell A1 of sheet evaluatierooster_NL
rs.Close
Set rs = Nothing
Set cn = Nothing
How to&Answers:

I suggest running the macro separately then connecting to he file and copying the data.

E.g. from http://www.ozgrid.com/forum/showthread.php?t=13173

Sub ExportAccessData()

    Dim mydb As Object

    Set mydb = GetObject("G:\mgai\pertrac\database\StrategyResearch.mdb") 
    mydb.Application.Run "ExportData"  
    mydb.Application.Quit 
    Set mydb = Nothing

End Sub

E.g. from http://support.microsoft.com/kb/131921

Sub Run_Access_Macro()

    Shell("c:\access\msaccess.exe c:\access\sampapps\nwind.mdb")
    Chan = DDEInitiate("MSACCESS", "system") 
    Application.ActivateMicrosoftApp xlMicrosoftAccess
    DDEExecute Chan, "Sample AutoExec"
    Application.DDETerminate Chan

End Sub