[英]Update SQL from Excel sheet using VBA
I am trying to update some records in SQL from excel sheet using VBA. 我正在尝试使用VBA从excel表更新SQL中的一些记录。 I have a lot of records in the excel sheet so this is why I want to automate this. 我在excel工作表中有很多记录,所以这就是为什么我要自动化它的原因。 Below is a sample of the field I want to update "rmn_dr". 以下是我要更新“ rmn_dr”的字段的示例。 "t_id" is unique in both tables. “ t_id”在两个表中都是唯一的。 I want to update "rmn_dr" in the SQL "Job" table with values from "Excel Sheet" 我想用“ Excel Sheet”中的值更新SQL“ Job”表中的“ rmn_dr”
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? 有人可以为我提供VBA代码吗? Thanks 谢谢
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. 假设Excel工作表上的数据是从a1单元格(包括字段)中列出的。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.