Search code examples
excelvbams-jet-ace

Using 'Insert Into' SQL Statement with column names on Excel Worksheet with ACE OLEDB fails


So, I want to get disciplined in how I store data to worksheets and was wanting to use the SQL OLEDB Provide for Excel and standard SQL statements. Insert into with column names does not work, yet, for me at least. Some code demonstrates the problem. Expecting both forms shown here to work W3 Schools SQL INSERT INTO Statement

Option Explicit

Sub MinimalCompleteVerifiableExample()
    'Tools->References "Microsoft ActiveX Data Objects 2.8 Library"

    Dim wsNew As Excel.Worksheet
    Set wsNew = ThisWorkbook.Worksheets.Add

    wsNew.Cells(1, 1) = "TimeStamp"
    wsNew.Cells(1, 2) = "Path"


    Dim oConn As ADODB.Connection
    Set oConn = New ADODB.Connection

    Debug.Assert UBound(Split(ThisWorkbook.Name, ".")) > 0  '* Workbook needs to be saved

    oConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
           "Data Source=" & ThisWorkbook.FullName & ";" & _
           "Extended Properties='Excel 12.0 Macro'"


    Dim rsTestRead As ADODB.Recordset
    Set rsTestRead = New ADODB.Recordset
    rsTestRead.Open "Select * from [" & wsNew.Name & "$] AS P", oConn, adOpenStatic

    Debug.Assert oConn.Errors.Count = 0
    Debug.Assert rsTestRead.Fields.Item(0).Name = "TimeStamp"
    Debug.Assert rsTestRead.Fields.Item(1).Name = "Path"

    Dim sSQL As String
    sSQL = "insert into [" & wsNew.Name & "$] (TimeStamp,Path) VALUES ('31-Dec-2015','C:\temp');"  'DOES NOT WORK
    'sSQL = "insert into [" & wsNew.Name & "$]  values ('25-Dec-2015','C:\temp')" 'works

    Stop
    oConn.Execute sSQL
    Debug.Assert oConn.Errors.Count = 0
    Stop
End Sub

On gets an error message of "Syntax error in INSERT INTO statement."


Solution

  • Ah.

    It seems one adds square brackets around the column names

        Dim sSQL As String
        sSQL = "insert into [" & wsNew.Name & "$] ([TimeStamp],[Path]) VALUES ('31-Dec-2015','C:\temp');"