Update SQL from Excel sheet using VBA

北战南征 提交于 2019-12-11 15:44:53

问题


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:


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


来源:https://stackoverflow.com/questions/52565661/update-sql-from-excel-sheet-using-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!