Tuesday, November 21, 2017

Insert Data Using Named range in SQL server table Excel VBA

Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
With cn
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .ConnectionString = "Data Source=C:\temp\JW_E&PM_041.xlsx;" & _
"Extended Properties=Excel 12.0;"
    .Open
End With

sSQL = "SELECT * FROM testrangdata"
'sSQL = "SELECT * FROM [Sheet1$A1:E46]"
Set oRs = New ADODB.Recordset
oRs.Open sSQL, cn, adOpenStatic, adLockBatchOptimistic, adCmdText

Set cn2 = CreateObject("ADODB.Connection")
    With cn2
        .CursorLocation = adUseClient
        .Open "Driver={SQL Server};Server=Server1\SQL1; Database=mydb; UID=bbbbb; PWD=MMMMM"
        .CommandTimeout = 0
        oRs.MoveFirst
        Do While Not oRs.EOF
        Debug.Print oRs.Fields(1)
     
            .Execute "INSERT INTO budget.dbo.delthisTEMP_TABLE ( [BU] ) VALUES ('" & oRs.Fields(1) & "')"
            oRs.MoveNext
            Loop
    End With

cn.Close

No comments: