|
楼主 |
发表于 2015-1-31 13:25
|
显示全部楼层
ppl123 发表于 2015-1-31 12:46
版主你好,能帮我在电话簿管理系统(以access为数据库) 添加一个一键导入excel数据的功能吗,因为我的数据量 ...
在工作簿中插入一张新表——数据库,更新Access中已经存在的记录,添加不存在的记录:- Sub updateaddRecords()
- Dim cnn As New ADODB.Connection
- Dim rs As New ADODB.Recordset
- Dim myTable As String
- Dim strTemp As String
- Dim SQL As String
- Dim strMsg As String
- Dim aField As Variant
- Dim i As Long
- myTable = "数据库"
- cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & ThisWorkbook.Path & "\电话号码.mdb"
- SQL = "SELECT B.姓名 FROM " & myTable & " A,[Excel 8.0;Database=" & ThisWorkbook.FullName & ";].[" & ActiveSheet.Name & "$" _
- & Range("A1").CurrentRegion.Address(0, 0) & "] B WHERE A.姓名=B.姓名"
- Set rs = New ADODB.Recordset
- rs.Open SQL, cnn, adOpenKeyset, adLockOptimistic
- If rs.RecordCount > 0 Then
- aField = Intersect(Range("A1").CurrentRegion, Rows(1))
- For i = 2 To UBound(aField, 2)
- strTemp = strTemp & ",a." & aField(1, i) & "=b." & aField(1, i)
- Next
- SQL = "UPDATE " & myTable & " A,[Excel 8.0;Database=" & ThisWorkbook.FullName & ";].[" & ActiveSheet.Name & "$" _
- & Range("A1").CurrentRegion.Address(0, 0) & "] B SET " & Mid(strTemp, 2) & " WHERE A.姓名=B.姓名"
- cnn.Execute SQL
- strMsg = rs.RecordCount & "条记录已更新!"
- End If
- If Range("A1").CurrentRegion.Rows.Count - 1 > rs.RecordCount Then
- SQL = " SELECT A.* FROM [Excel 8.0;Database=" & ThisWorkbook.FullName & ";].[" & ActiveSheet.Name & "$" & Range("A1").CurrentRegion.Address(0, 0) _
- & "] A LEFT JOIN " & myTable & " B ON A.姓名=B.姓名 WHERE B.姓名 IS NULL"
- Set rs = New ADODB.Recordset
- rs.Open SQL, cnn, adOpenKeyset, adLockOptimistic
- If rs.RecordCount > 0 Then
- SQL = "INSERT INTO " & myTable & SQL
- cnn.Execute SQL
- strMsg = strMsg & vbCrLf & rs.RecordCount & "条记录已添加到数据库!"
- End If
- End If
- MsgBox strMsg, vbInformation, "提示"
- rs.Close
- cnn.Close
- Set rs = Nothing
- Set cnn = Nothing
- End Sub
复制代码 |
|