Consulting

Results 1 to 2 of 2

Thread: How to use the SQL Insert Into Statement w/Excel

  1. #1
    Microsoft Word MVP 2003-2009 VBAX Guru gmaxey's Avatar
    Joined
    Sep 2005
    Posts
    3,340
    Location

    How to use the SQL Insert Into Statement w/Excel

    I'm practically virgin in this fields, so be gentle.

    I'm trying to figure out if it is possible to write a new record to an Excel database using ADO. The following is what I've cobbled together, but I know that I am simply missing a critical piece or maybe even the whole point.

    Thanks.

    Sub Test()
    Dim oConn As Object
    Dim strSQL As String
    Set oConn = GetExcelConnection("D:\Testing.xlsx", False)
    strSQL = "INSERT INTO [Sheet1$] (column1,column2,column3) VALUES (value1,value2,value3);"
    oConn.Execute strSQL
    If oConn.State = 1 Then oConn.Close
    Set oConn = Nothing
    End Sub
    Private Function GetExcelConnection(ByVal Path As String, _
                                        Optional ByVal Headers As Boolean = True) As Object
    Dim strConn As String
    Dim oConn As Object
    Set oConn = CreateObject("ADODB.Connection")
      strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                "Data Source=" & Path & ";" & _
                "Extended Properties=""Excel 12.0 Xml;HDR=NO"";"
      oConn.Open ConnectionString:=strConn
      Set GetExcelConnection = oConn
    End Function
    Greg

    Visit my website: http://gregmaxey.com

  2. #2
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,720
    Location
    As long as you have at least three columns of data present already, you can use:
    [vba] strSQL = "INSERT INTO [Sheet1$] ([F1],[F2],[F3]) VALUES ('value1','value2','value3');"
    [/vba]
    Be as you wish to seem

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •