0% found this document useful (0 votes)
29 views

'Step 1: Declare Your Variables: Excel VBA Code

This VBA code runs a parameterized query in Access and copies the results to an Excel spreadsheet. It defines the database and query, sets the parameter values from cells, opens the query, clears the destination sheet, copies the recordset to the sheet, and adds the field names as column headers. When complete, it displays a message that the query has run.

Uploaded by

EdsonBernardo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

'Step 1: Declare Your Variables: Excel VBA Code

This VBA code runs a parameterized query in Access and copies the results to an Excel spreadsheet. It defines the database and query, sets the parameter values from cells, opens the query, clears the destination sheet, copies the recordset to the sheet, and adds the field names as column headers. When complete, it displays a message that the query has run.

Uploaded by

EdsonBernardo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Excel VBA code:

Sub RunParameterQuery()
'Step 1: Declare your variables
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
Set MyDatabase = DBEngine.OpenDatabase _
("C:\Users\SESA273168\Hasznos Holmi\_CONTROLLING\DATABASE\ORDER\PW.accdb")
Set MyQueryDef = MyDatabase.QueryDefs("AD-HOC")
'Step 3: Define the Parameters
With MyQueryDef
.Parameters("[Enter Customer]") = Range("J22").Value
.Parameters("[Enter Year]") = Range("J23").Value
End With
'Step 4: Open the query
Set MyRecordset = MyQueryDef.OpenRecordset
'Step 5: Clear previous contents
Sheets("data").Select
ActiveSheet.Range("A1:E1000000").ClearContents
'Step 6: Copy the recordset to Excel
ActiveSheet.Range("A1").CopyFromRecordset MyRecordset
'Step 7: Add column heading names to the spreadsheet
For i = 1 To MyRecordset.Fields.Count
ActiveSheet.Cells(1, i).Value = MyRecordset.Fields(i - 1).Name
Next i

MsgBox "Your Query has been Run"


End Sub

Access query:

You might also like