|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
- 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 = "select " & Mid(s, 2) & " from [Excel 8.0;Database=" & ThisWorkbook.FullName & "].[" & ActiveSheet.Name & "$" & [a1].CurrentRegion.Address(0, 0) & "] group by 姓名,手机"
- SQL = "insert into temp " & SQL
- cnn.Execute SQL '把工作表中不重复记录(相同记录取最后的)导入到临时表
-
- '下面是临时表的数据添加或者追加到通讯录---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- SQL = "update 通讯录 a,temp b set " & Mid(s2, 2) & " where a.姓名=b.姓名 and a.手机=b.手机"
- cnn.Execute SQL '不判断,更新可能存在的姓名和手机记录
- SQL = "select a.* from (select " & Mid(s, 2) & " from temp 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
-
- SQL = "delete from temp"
- cnn.Execute SQL '最后删除临时表中的记录
- rs.Close
- cnn.Close
- Set rs = Nothing
- Set cnn = Nothing
- End Sub
复制代码 |
|