|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
Public Sub 实例7_11()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim i As Long
Dim mydata As String, mytable As String, SQL As String
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheets("sheet1")
mydata = "UFDATA_602_2014"
mytable = "Department"
Set cnn = New ADODB.Connection
With cnn
.ConnectionString = "Provider=SQLOLEDB.1;" _
& "User ID=sa;" _
& "Password = ;" _
& "Data Source=7WCKO7IUPQAVPNE;" _
& "Initial Catalog=" & mydata
.Open
End With
n = ws.Range("A65536").End(xlUp).Row
For i = 2 To n
SQL = "select * from " & mytable _
& " where cDepCode='" & Trim(ws.Cells(i, 1).Value) & "'" _
& " and bDepEnd='" & Trim(ws.Cells(i, 2).Value) & "'" _
& " and cDepName='" & Trim(ws.Cells(i, 3).Value) & "'" _
& " and iDepGrade='" & Trim(ws.Cells(i, 4).Value) & "'"
Set rs = New ADODB.Recordset
rs.Open SQL, cnn, adOpenKeyset, adLockOptimistic
If rs.EOF And rs.BOF Then
rs.AddNew
For j = 1 To rs.Fields.Count
rs.Fields(j - 1) = Trim(ws.Cells(i, j).Value)
Next j
rs.Update
Else
For j = 1 To rs.Fields.Count
rs.Fields(j - 1) = Trim(ws.Cells(i, j).Value)
Next j
rs.Update
End If
Next i
MsgBox "数据保存完毕!", vbInformation, "保存数据"
rs.Close
cnn.Close
Set wb = Nothing
Set ws = Nothing
Set rs = Nothing
Set cnn = Nothing
End Sub
请教高手修改红色的代码,当excel数据表中 cDepCode列的编码与数据库表中的代码相同时,修改整条记录,不相同时添加整条记录
|
|