I am trying to automate a process of exporting data from a database in MS Access to excel using VBA. When I do it regularly (excuse my lack of proper verbiage as I am a complete newb at this), I start by creating a query linking two tables. I double click the asterisk to show the tables. I add one of the column headers as a field in the query and add the criteria I need. Then I run the query and export it to excel.
I have tried using Google to solve my issue and I have tried to copy and paste the SQL from the query into VBA. I think the latter could work but it is missing the first step I think but I am not sure what that step is.
Edit: This is one attempt I've made with help from the internet.
Sub createQry()
Dim db As DAO.Database
Set db = CurrentDb
Dim qdf As DAO.QueryDef
Dim newSQL As String
newSQL = "Select * From [(MR)Events2025] And [(MR)EventMemo2025] WHERE [EvtDate]= >=#1/1/2022# And <=#1/31/2022#"
End Sub
I want to make it to where I can click a button in excel and it run the process of creating the query in access and then exporting it to excel. The file changes monthly with updated data and I would like to not have to do the same thing every month and just click a button to get the data I want. If it were all in excel I would be fine because of the record macro feature but it doesn't seem to work outside of excel.
I guess what I want the code to do is open the access database when I click a button in excel, create the query in access (this includes copying a date range from the cell I have selected and pasting it in the criteria portion of the query, or just having that part of the query equal the selected cell in excel), and export the data from the query to excel. I can figure the other stuff I want to do via the macro recorder.
The below creates the query for me, now I have to export it to excel.
Sub CreateQueryDefX()
Dim dbsAssetManagement As Database
Dim qdfTemp As QueryDef
Dim qdfNew As QueryDef
Set dbsAssetManagement = OpenDatabase("C:(deleted file location for privacy)AssetManagement.accdb")
With dbsAssetManagement
Set qdfNew = .CreateQueryDef("NewQueryDef", _
"SELECT [(MR)Events2025].*, [(MR)EventMemo2025].* FROM [(MR)Events2025] INNER JOIN [(MR)EventMemo2025] ON [(MR)Events2025].MCN = [(MR)EventMemo2025].MCN_ID WHERE ((([(MR)Events2025].EvtDate) >=#1/1/2022# And ([(MR)Events2025].EvtDate)<=#1/31/2022#))")
End With
End Sub