I am trying to configure an SQL UPDATE query in a VBA program.
Basically, I update a table in the current workbook from a table in a closed workbook. This works great using the below query only if the source workbook is a .xls file :
Sub UPDATEQUERY(SourcePath As String, SourceSheet As String, TargetSheet As String, _
Columns As String, Filter As String)
Dim Cn As ADODB.Connection
Dim QUERY_SQL As String
Dim CHAINE_HDR As String
Dim STRCONNECTION As String
CHAINE_HDR = "[Excel 8.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=1;Extended Properties='HDR=YES;'] "
Set Cn = New ADODB.Connection
QUERY_SQL = _
"UPDATE [" & TargetSheet & "$] INNER JOIN (SELECT * FROM [" & SourceSheet & "$] " & _
"IN '" & SourcePath & "' " & CHAINE_HDR & ") t2 " & _
"ON [" & TargetSheet & "$].id = t2.id " & _
"SET [" & TargetSheet & "$].ColA = t2.ColA "
STRCONNECTION = _
"Driver={Microsoft Excel Driver (*.xls)};" & _
"DriverId=790;" & _
"Dbq=" & ThisWorkbook.FullName & ";" & _
"DefaultDir=" & ThisWorkbook.FullName & ";ReadOnly=False;"
Cn.Open STRCONNECTION
Cn.Execute (QUERY_SQL)
'--- Fermeture connexion ---
Cn.Close
Set Cn = Nothing
End Sub
So as to use .xlsx file as the source file I want to connect to the source using the same provider/driver that I use to connect to the current wb, that is MSDASQL.1 instead of Microsoft.ACE.OLEDB.12.0. Indeed If I only set the 'CHAINE_HDR' to Excel 12.0
I get a "ISAM driver not found".
To achieve this I'm trying to use OPENROWSET like this :
Sub UPDATEQUERY(SourcePath As String, SourceSheet As String, TargetSheet As String, _
Columns As String, Filter As String)
Dim Cn As ADODB.Connection
Dim QUERY_SQL As String
Dim STRCONNECTION As String
Dim STRCONNECTION_SOURCE As String
STRCONNECTION_SOURCE = _
"'MSDASQL.1'," & _
"'Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=" & SourcePath & ";'," & _
"'SELECT * FROM [Data$]'"
Set Cn = New ADODB.Connection
QUERY_SQL = _
"UPDATE [" & TargetSheet & "$] INNER JOIN (SELECT * FROM OPENROWSET(" & STRCONNECTION_SOURCE & ")) t2 " & _
"ON [" & TargetSheet & "$].id = t2.id " & _
"SET [" & TargetSheet & "$].ColA = t2.ColA "
STRCONNECTION = _
"Driver={Microsoft Excel Driver (*.xls)};" & _
"DriverId=790;" & _
"Dbq=" & ThisWorkbook.FullName & ";" & _
"DefaultDir=" & ThisWorkbook.FullName & ";ReadOnly=False;"
Cn.Open STRCONNECTION
Cn.Execute (QUERY_SQL)
'--- Fermeture connexion ---
Cn.Close
Set Cn = Nothing
End Sub
However I get an "Synthax error in from clause".
How to properly set up my sql query ?
Thanks