I'm new to VBA and I'm trying to write code that will take a SQL query and append that data to an existing excel file. I'm using books to try and teach myself how to do this. My latest problem is getting a runtime error 2147217900, where it is saying that I have extra ) in my query. I need help in refining this VBA code to get it to work.
Sub GetAccessData_With_SQL_GetObject_With_Excel()
'Step 1: Declare your Variables
Dim MyConnect As String
Dim MyRecordset As ADODB.Recordset
Dim MyQueryDef As DAO.QueryDef
Dim MyDatabase As DAO.Database
Dim MySQL As String
Dim MyRange As String
Dim Db As Database
Dim xl As Excel.Application
Set xl = New Excel.Application
Dim xlwkbk As Excel.Workbook
Dim xlsheet As Excel.Worksheet
Dim strInput As String
Dim strMsg As String
'Sep 2: Declare your connection string
MyConnect = "Provider=Microsoft.ACE.OLEDB.12.0; Persist Security Info = False;Data Source= Q:\WWC Common\TAMPA Files\LSG Month-End FG Inventory Excess-Reserve Analysis.accdb; User ID = Admin;"
'Step 3: Build Input Box
strMsg = "What Fiscal Month?"
strInput = InputBox(Prompt:=strMsg, Title:="Period")
'Step 4: Build Your SQL Statement
MySQL = "Select [slq-Item count].[Fiscal Year],[slq-Item count].[Fiscal Month], " & _
"Sum([slq-Item count].CountOfitem) As ItemCount,Sum([slq-Item count].[SumOfGross Units]) As Units " & _
"From [slq-Item count] " & _
"Group By [slq-Item count].[Fiscal Year],[slq-Item count].[Fiscal Month] " & _
"Having(([slq-Item count].[Fiscal Year])=2012) And(([slq-Item count].[Fiscal Month])= " & Period & ")"
'Step 4: Instantiate and specify your recordset
Set MyRecordset = New ADODB.Recordset
MyRecordset.Open MySQL, CurrentProject.Connection 'adOpenStatic, adLockOptimistic)
'Step 5: Instantiate Excel. If Excel isn't Loaded, Error # 429 occurs.
Set xl = GetObject(, "Excel.Application")
'Step 6: Open ItemIdCount.xlsx
Set xlwkbk = xl.Workbooks.Open("Q:\WWC Common\TAMPA Files\ItemIDCount.xlsx", , True)
Set xlsheet = xlwkbk.Worksheets("ItemIdCnt")
'Step 7: Find First empty Row and use that to build a dynamic range
Sheets("ItemIdCnt").Select
MyRange = "F" & _
ActiveSheet.Cells.SpecialCells(XlCellTypeLastCell) .Row + 1
'Step 8: Copy the recordset to First Empty Row
ActiveSheet.Range(MyRange).CopyFromRecordset MyRecordset
'Step 9: e variables
Set xlsheet = Nothing
Set xlwkbk = Nothing
Set xlApp = Nothing
Set Db = Nothing
MyRecordset.Close
End Sub