|
Sub 将工作表数据自动导入ACCESS数据库()
'引用Microsoft ActiveX Data Objects 2.x Library
Dim cnn As New ADODB.Connection, rs As New ADODB.Recordset, SQL As String, strMsg As String
' cnn.Open "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\数据库.accdb"
Dim DatabaseFuPass As String: DatabaseFuPass = ThisWorkbook.Path & "\数据库.accdb"
Const myPass As String = "1234"
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Jet OLEDB:Database Password=" & myPass & ";Data Source=" & DatabaseFuPass
SQL = "SELECT A.* FROM [Excel 12.0;Database=" & ThisWorkbook.FullName & ";].[数据库$A1:X" & Sheets("数据库").Range("b" & Sheets("数据库").Rows.Count).End(xlUp).Row _
& "] A LEFT JOIN (Select * From 数据库) D ON A.单号=D.单号 WHERE D.单号 IS NULL"
rs.Open SQL, cnn, adOpenKeyset, adLockOptimistic
If rs.RecordCount > 0 Then
SQL = "INSERT INTO 数据库 " & SQL
cnn.Execute SQL
strMsg = rs.RecordCount & "条记录已添加到数据库!"
Else
strMsg = "没有发现可以插入的记录!"
End If
MsgBox strMsg, vbInformation, "提示"
rs.Close: cnn.Close
Set rs = Nothing: Set cnn = Nothing
End Sub |
|