|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
沉默的流星 发表于 2013-4-18 05:47
老师:数据库里的更新,而且保证是唯一的值,这个效果已经达到了,但是还有个问题没有解决,就是工作表里, ... - Sub 插入数据()
- Dim tt
- tt = Timer
- Dim cnn As Object, rs As Object, SQL$
- Dim arr, i&, s$, s2$, t$
- arr = Range("A1", [iv1].End(1))
- For i = 1 To UBound(arr, 2)
- If arr(1, i) <> "姓名" And arr(1, i) <> "手机" Then
- s = s & ",last(" & arr(1, i) & ") as " & arr(1, i)
- s2 = s2 & ",a." & arr(1, i) & "=b." & arr(1, i)
- Else
- s = s & "," & arr(1, i)
- End If
- Next
- Set cnn = CreateObject("adodb.connection")
- cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & ThisWorkbook.Path & "\通讯录.mdb"
- SQL = "update 通讯录 a,[Excel 8.0;Database=" & ThisWorkbook.FullName & "].[" & ActiveSheet.Name & "$" & [a1].CurrentRegion.Address(0, 0) & "] b set " & Mid(s2, 2) & " where a.姓名=b.姓名 and a.手机=b.手机"
- cnn.Execute SQL '不判断,更新可能存在的姓名和手机记录
- SQL = "select a.* from (select " & Mid(s, 2) & " from [Excel 8.0;Database=" & ThisWorkbook.FullName & "].[" & ActiveSheet.Name & "$" & [a1].CurrentRegion.Address(0, 0) _
- & "] group by 姓名,手机) a left join 通讯录 b on a.姓名=b.姓名 and a.手机=b.手机 where b.姓名 is null"
- Set rs = CreateObject("adodb.recordset")
- rs.Open SQL, cnn, 1, 3
- If rs.RecordCount Then
- SQL = "insert into 通讯录 " & SQL
- cnn.Execute SQL
- MsgBox rs.RecordCount & "行数据已经添加到数据库!用时" & Timer - tt & "秒", vbInformation
- Else
- MsgBox "工作表的数据数据库中已经存在。", vbInformation
- End If
- rs.Close
- cnn.Close
- Set rs = Nothing
- Set cnn = Nothing
- End Sub
复制代码 |
|