|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
數據庫內未存在此單號,則新建數據
但無法新建數據
- '引用Microsoft ActiveX Data Objects 2.x Library
- Sub updateaddRecords2007()
- Dim cnn As New ADODB.Connection
- Dim rs As New ADODB.Recordset
- Dim myPath As String
- Dim myTable As String
- Dim strTemp As String
- Dim arrFields As Variant
- On Error Resume Next
-
- Application.ScreenUpdating = False
- myPath = "\\資料庫\資料庫.accdb"
- myTable = "客戶清單"
- ' On Error GoTo errmsg
- cnn.Open "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" & myPath '連接數據庫
-
- arrFields = Range("A1:as1") '工作表中的字段名寫入數組
-
- '生成更新字符串,如:a.姓名=b.姓名,a.性別=b.性別,……
- For i = 2 To UBound(arrFields, 2)
- strTemp = strTemp & ",a." & arrFields(1, i) & "=b." & arrFields(1, i)
- Next
- '生成更新SQL語句(請注意Office2007後需要加imex=0參數)
- SQL = "update " & myTable & " a,[Excel 12.0;imex=0;Database=" & ActiveWorkbook.FullName & "].[收款跟催$" _
- & Range("a1").CurrentRegion.Address(0, 0) & "] b set " & Mid(strTemp, 2) & " where a.單號=b.單號"
- cnn.Execute SQL '不判斷,更新可能存在的「單號」
-
- '生成數據庫不存在記錄的SQL語句
- SQL = "select a.* from [Excel 12.0;Database=" & ActiveWorkbook.FullName & "].[收款跟催$" & 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 '插入新記錄SQL語句
- cnn.Execute SQL
- 'MsgBox rs.RecordCount & "行數據已經添加到數據庫!", vbInformation, "添加數據"
- Else
- 'MsgBox "工作表的數據數據庫中已經存在。", vbInformation, "添加數據失敗"
- End If
-
- '關閉連接釋放內存
- rs.Close
- cnn.Close
- Set rs = Nothing
- Set cnn = Nothing
- Application.ScreenUpdating = True
-
- Exit Sub
- errmsg:
- MsgBox Err.Description, , "錯誤報告"
- End Sub
复制代码
|
|