I am using SQL in VBA inside MS Excel to query a spreadsheet. I want to check for a record's existence, and either update or insert the record as appropriate. This calls for:
IF EXISTS (condition) UPDATE ELSE INSERT
The "Test" portion doesn't work, and raises an error. In debugging, I have eliminated all Excel elements from the query, resulting in the following code:
Dim conn As New ADODB.Connection
Dim recset As New ADODB.Recordset
Dim scmd As String
scmd = "IF EXISTS (SELECT 'Test')"
scmd = scmd + "SELECT 'Found' "
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & _
"Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
conn.Execute (scmd)
conn.Close
This generates the SQL statement:
IF EXISTS (SELECT 'Test') SELECT 'Found'
The resulting error is:
Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.
I tested the same statement in MS SSMS, and it worked properly. Having eliminated both my Excel spreadsheet and the SQL statement as problems, it seems the problem is in a quirk of VBA. How do I fix this?
For what it's worth, the connection string works properly for pure SELECT queries in my project.
Testqualify as a column name or a table name? Can you use[]with proper column and table names and try the query?IF, iircIIF()worksTest.IF EXISTS