I have this code in my database which is working fine. However when I copy it to another database and change the query name to the correct one I get the following error message.
Run-time error '3061':
Too few parameters. Expected 1.
If I debug it highlights this line of the code
Set MyRecordset = MyQueryDef.OpenRecordset
Any idea why??
Code:Private Sub ExcelRec_Click() '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 = CurrentDb Set MyQueryDef = MyDatabase.QueryDefs("QueryName") 'Query name in the database 'Step 3: Open the query Set MyRecordset = MyQueryDef.OpenRecordset 'Step 4: Clear previous contents Dim xlApp As Object Set xlApp = CreateObject("Excel.Application") With xlApp .Visible = True .Workbooks.Add .Sheets("Sheet1").Select 'Step 5: Copy the recordset to Excel .ActiveSheet.Range("A2").CopyFromRecordset MyRecordset 'Step 6: Add column heading names to the spreadsheet For i = 1 To MyRecordset.Fields.Count xlApp.ActiveSheet.Cells(1, i).Value = MyRecordset.Fields(i - 1).Name Next i xlApp.Cells.EntireColumn.AutoFit End With MsgBox "Export has been successful", vbInformation, "Sample" End Sub