I'm currently creating a function in VBA that generates a query automatically if you press a button. The code runs without error, initially, but when I fill out the input boxes correctly, it pops up a window that says "Please Enter Microsoft Access Database Engine OLE DB Initialization Information", and then gives me the choice to fill in data source, user admin, password, provider string, and open mode. Each box is filled out besides password. I don't have access to this information, but it shouldn't in the first place, pop this wndow up. In the code, I reference to an excel sheet which pulls certain information from the report (specifically the columns) and creates a query using these columns where the month and year are a certain date. Then, I aim to move the query to a different Excel workbook, and list them in a sheet over there. However, I continue to receive the same error (When I press the cancel button in the window, the place of error is on the .Refresh BackgroundQuery.). This is the code :
Sub GenerateQuery()
Dim targetMonth As String
targetMonth = InputBox("Enter the target month (e.g., January):")
Select Case LCase(targetMonth)
Case "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"
Case Else
MsgBox "Please enter a valid month name."
' Prompt user for input again or exit the code, based on your requirement
Exit Sub ' Exits the sub-routine
End Select
Dim targetYear As String
targetYear = InputBox("Enter the target year (e.g., 2023):")
If Not IsNumeric(targetYear) Or Len(targetYear) <> 4 Then
MsgBox "Invalid year format. Please enter a four-digit year.", vbExclamation
Exit Sub ' Exit the code if input is invalid
End If
Dim columnList As String
columnList = "[Invoice Id], [Invoice Date], FORMAT([Invoice Date], ""mmm-dd"") AS [Formatted Date], [Serial], [Purch Id], [Item Id], [Sell Price], [Revenue Share], [Vendor]"
Dim query As String
query = "SELECT " & columnList & " FROM [tbl_Cons_Rpt] WHERE MONTH([Invoice Date]) = " & Month(DateValue(targetMonth & " 1")) & " AND YEAR([Invoice Date]) = " & targetYear & " AND [Vendor] = 'V005501 - Atlantic Broadband ARP'"
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Open("C:\Users\notgonnashow.xlsx")
targetWorkbook.Sheets("qry_ABB1").UsedRange.ClearContents
Dim tableDestination As Range
Set tableDestination = targetWorkbook.Sheets("qry_ABB1").Range("A1")
With targetWorkbook.Sheets("qry_ABB1").ListObjects.Add( _
SourceType:=xlSrcQuery, _
Source:="OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & targetWorkbook.FullName & ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";", _
Destination:=tableDestination).QueryTable
.CommandType = xlCmdSql
.CommandText = query
.Refresh BackgroundQuery:=False
End With
targetWorkbook.Close SaveChanges:=True ' Modify later if needed
End Sub
Not sure whats going on. Any help would be appreciated to fix this problem. Thanks!