|
Sub ImportDataFromExcelToSQLServer()
' 定义连接字符串
Dim conn As New ADODB.Connection
Dim connString As String
connString = "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=zff_2023;User ID=sa;Password=123456;"
' 打开数据库连接
conn.ConnectionString = connString
conn.Open
' 定义 SQL 语句
Dim sql As String
sql = "SELECT * FROM td_123 WHERE gmsfh = ?"
' 获取 Excel 数据范围
Dim lastRow As Long
lastRow = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Row
Dim dataRange As Range
Set dataRange = Range("D2:E" & lastRow)
' 定义参数对象
Dim cmd As New ADODB.Command
Set cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = sql
cmd.Parameters.Append cmd.CreateParameter(, adVarChar, adParamInput, 50, "")
' 遍历数据范围,进行比对和数据写入
Dim row As Range
Dim rs As New ADODB.Recordset
For Each row In dataRange.Rows
cmd.Parameters(0).Value = row.Cells(1, 1).Value
' 查询数据库
rs.Open cmd, , adOpenKeyset, adLockOptimistic
If Not rs.EOF Then
' 如果找到匹配的记录,则写入 Excel 表格中 E 列到数据库的 zfqk 字段
Do While Not rs.EOF
rs.Fields("zfqk").Value = row.Cells(1, 2).Value
rs.Update
rs.MoveNext
Loop
End If
rs.Close
Next row
' 关闭连接
conn.Close
Set conn = Nothing
End Sub
|
|