Hi
I am getting a syntax error in FROM clause when I attempt to run some VBA with sql Join.
I get no errors when attempting simple select queries on either table.
The tables are as below.
NameL
ID NameV Age
1 Mark 30
2 George 22
3 Andrew 20
NameR
ID NameW Salary
1 mark 100000
2 George 500000
3 Arnold 50000
The code is as follows:
Sub ConnectAccessJoin()
Dim MyConnection As ADODB.Connection
Dim MyRecordset As ADODB.Recordset
Dim MyQuery As String
Set MyConnection = New ADODB.Connection
Set MyRecordset = New ADODB.Recordset
MyConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=C:\Users\mark0\OneDrive\Documents\ASampleDatabase.accdb"
MyQuery = "Select * FROM NameR Join NameL ON (NameV=NameW);" 'backtick required if table name is an SQL reserved word or table name has spaces in it. ie `Names` is a reserved word and `Asset List` has gaps
' MyQuery = "Select ID, NameW FROM NameR where NameW = 'Mark';" 'backtick required if table name is an SQL reserved word or table name has spaces in it. ie `Names` is a reserved word and `Asset List` has gaps
' MyQuery = "Select * FROM NameR;" 'backtick required if table name is an SQL reserved word or table name has spaces in it. ie `Names` is a reserved word and `Asset List` has gaps
'Open the connection
MyConnection.Open MyConnectionString
'Execute the query
Set MyRecordset = MyConnection.Execute(MyQuery)
'Copy the output of query in sheet1
' The following code extracts the field names from the table
' With Sheets("Sheet5") 'With can be used or not. If it is used then put a full stop in front of Cells(2,i).Value....
For i = 1 To MyRecordset.Fields.Count
Cells(2, i).Value = MyRecordset.Fields(i - 1).Name 'fields is a 0 based collection
Next i
' .Range("A3").CopyFromRecordset MyRecordset
'End With
Range("A3").CopyFromRecordset MyRecordset
' Worksheets("Sheet5").Range("A3").CopyFromRecordset MyRecordset 'You can choose to reference the worksheet or not depends if you are going to another sheet
'Closing the connection and setting the values of declared variables as Nothing or simply to NULL.
MyRecordset.Close
Set MyRecordset = Nothing
MyConnection.Close
Set MyConnection = Nothing
End Sub
Any ideas as to what I am doing incorrect?
Both database and excel file with code are attached
thanks
Bookmarks