Running Existing Query in excel from Access

Felipe84

New Member
Joined
Sep 23, 2014
Messages
1
I am trying to run a query from access in excel so i dont have to do a manual copy and paste. I keep getting "Invalid SQL statement; expected 'Delete, insert, procedure, select, or update." This is what i have done.

Option Explicit


Sub RunExistingQuery()


'Declaring the necessary variables.
Dim con As Object
Dim rs As Object
Dim AccessFile As String
Dim strQuery As String

'Disable screen flickering.
Application.ScreenUpdating = False

'Specify the file path of the accdb file. You can also use the full path of the file like:
'AccessFile = "C:\Users\Christos\Desktop\Sample.accdb"
AccessFile = "H:\MERCHANDISING\ReBuyers Shared\Rebuyers DBS.mdb"

'Set the name of the query you want to run adn retrieve the data.
strQuery = "Symbols Y Items"

On Error Resume Next
'Create the ADODB connection object.
Set con = CreateObject("ADODB.connection")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "Connection was not created!", vbCritical, "Connection error"
Exit Sub
End If
On Error GoTo 0

'Open the connection.
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & AccessFile

On Error Resume Next
'Create the ADODB recordset object.
Set rs = CreateObject("ADODB.recordset")
'Check if the object was created.
If Err.Number <> 0 Then
'Error! Release the objects and exit.
Set rs = Nothing
Set con = Nothing
'Display an error message to the user.
MsgBox "Connection was not created!", vbCritical, "Connection error"
Exit Sub
End If
On Error GoTo 0

'Set thee cursor location.
rs.CursorLocation = 3 'adUseClient on early binding
rs.CursorType = 1 'adOpenKeyset on early binding

'Open the recordset.
rs.Open strQuery, con

If Not (rs.EOF And rs.BOF) Then
'Write the query values in the sheet.
Sheet2.Activate
Range("A2").CopyFromRecordset rs
Else
'Close the recordet and the connection.
rs.Close
con.Close
'Release the objects.
Set rs = Nothing
Set con = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'In case of an empty recordset display an error.
MsgBox "There are no records in the recordset!", vbCritical, "No Records"
Exit Sub
End If

'Close the recordet and the connection.
rs.Close
con.Close

'Release the objects.
Set rs = Nothing
Set con = Nothing

'Adjust the columns' width.
Columns("A:B").EntireColumn.AutoFit

'Enable the screen.
Application.ScreenUpdating = True


'Inform the user that the macro was executed successfully.
MsgBox "All data were successfully retrieved from the query " & strQuery & "!", vbInformation, "Done"


End Sub
 

Some videos you may like

Excel Facts

Did you know Excel offers Filter by Selection?
Add the AutoFilter icon to the Quick Access Toolbar. Select a cell containing Apple, click AutoFilter, and you will get all rows with Apple

Watch MrExcel Video

Forum statistics

Threads
1,114,236
Messages
5,546,656
Members
410,753
Latest member
Ian R
Top