|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
建议你搜索ADO,给你个例子吧
Sub leadin()
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim i As Long, n As Long, j As Long
Dim mydatabase As String, mytable As String, sql As String
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook '指定工作簿
Set ws = wb.Sheets("sheet1") '指定工作表名称
Application.ScreenUpdating = True
mydatabase = InputBox("请输入要导入的数据库名", "向数据库中导入数据") '指定数据库
mytable = InputBox("请输入要导入的工作表名", "向数据库中导入数据") '指定数据表
With cnn '建立与SQL Server数据库链接
.ConnectionString = "provider=sqloledb.1;" _
& "password=sa;" _
& "user id=sa;" _
& "datasource=lucas;" _
& "initial catalog=" & mydatabase
.Open
End With
n = ws.Range("a65536").End(xlUp).Row '获取要保存记录的行数
For i = 2 To n
'查询是否已存在某条记录
sql = "select * from " & mytable _
& " where SerialId='" & Trim(ws.Cells(i, 1).Value) & "'" _
& " and operid='" & Trim(ws.Cells(i, 2).Value) & "'" _
& " and operpws='" & Trim(ws.Cells(i, 3).Value) & "'" _
& " and gradeid='" & Trim(ws.Cells(i, 4).Value) & "'" _
& " and deptid='" & Trim(ws.Cells(i, 5).Value) & "'" _
& " and remark='" & Trim(ws.Cells(i, 6).Value) & "'" _
& " and checkgrant='" & Trim(ws.Cells(i, 7).Value) & "'" _
& " and upoperid='" & Trim(ws.Cells(i, 8).Value) & "'" _
& " and equid='" & Trim(ws.Cells(i, 9).Value) & "'"
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) = 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
Application.ScreenUpdating = True
End Sub |
|