Update SQL from Excel sheet using VBA

2019-08-22 00:24发布

I am trying to update some records in SQL from excel sheet using VBA. I have a lot of records in the excel sheet so this is why I want to automate this. Below is a sample of the field I want to update "rmn_dr". "t_id" is unique in both tables. I want to update "rmn_dr" in the SQL "Job" table with values from "Excel Sheet"

Excel Sheet
t_id          rmn_dr
310449           16
310450           120
310451           256
310452           165.2


JOB (SQL Table)
t_id          rmn_dr
310449           2
310450           5
310451           7
310452          0

Can someone help me with the VBA code please? Thanks

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-22 00:41

If each field is text, try the following.

The assumption is that the data on the Excel sheet is listed from a1 Cell, including fields.

Sub setDAtaToServer()
    Dim con As New ADODB.Connection
    Dim cmd As New ADODB.Command
    Dim rst As New ADODB.Recordset
    Dim i As Long
    Dim vDB As Variant
    Dim Ws As Worksheet

    con.ConnectionString = "Provider=SQLOLEDB.1;" _
             & "Server=(local);" _
             & "Database=JOB;" _
             & "Integrated Security=SSPI;" _
             & "DataTypeCompatibility=80;"

    con.Open


    Set cmd.ActiveConnection = con
    Set Ws = ActiveSheet

    vDB = Ws.Range("a1").CurrentRegion

    For i = 2 To UBound(vDB, 1)
        cmd.CommandText = "UPDATE JOB SET rmn_dr='" & vDB(i, 2) & "' WHERE t_id='" & vDB(i, 1) & "' "
        cmd.Execute
    Next i

    con.Close
    Set con = Nothing

End Sub
查看更多
登录 后发表回答