0

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 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.