|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
请测试:- Private Sub ComboBox1_DropButtonClick()
- ComboBox1.Column = Range("A9", Cells(9, Columns.Count).End(1)).Value
- End Sub
- Private Sub ComboBox2_DropButtonClick()
- ComboBox2.Column = Range("A9", Cells(9, Columns.Count).End(1)).Value
- End Sub
- Private Sub CommandButton1_Click()
- '引用Microsoft ActiveX Data Objects 2.x Library
- Dim cnn As New ADODB.Connection
- Dim rs As New ADODB.Recordset
- Dim SQL As String
- Dim myPath As String
- Dim myTable As String
- Dim UpdateFields As String
- Dim AddFields As String
- Dim arrFields As Variant
-
- If ComboBox1.ListIndex < 1 Then
- MsgBox "请选择测量点后面的字段!", vbCritical
- Exit Sub
- End If
- If ComboBox2.ListIndex <= ComboBox1.ListIndex Then
- MsgBox "请选择第一个复合框后面的字段!", vbCritical
- Exit Sub
- End If
-
- myPath = ThisWorkbook.Path & "\Database5.accdb"
- myTable = "BX5A"
-
- On Error GoTo errmsg
- cnn.Open "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" & myPath '连接数据库
- arrFields = Range("A9", Cells(9, Columns.Count).End(1)) '工作表中的字段名写入数组
-
- '生成更新字符串,添加字符串AddFields
- For i = ComboBox1.ListIndex + 1 To ComboBox2.ListIndex + 1
- UpdateFields = UpdateFields & ",a." & arrFields(1, i) & "=b." & arrFields(1, i)
- AddFields = AddFields & ",a." & arrFields(1, i)
- Next
-
- SQL = "update " & myTable & " a,[Excel 12.0;imex=0;Database=" & ActiveWorkbook.FullName & "].[Sheet1$" _
- & Range("a9").CurrentRegion.Address(0, 0) & "] b set " & Mid(UpdateFields, 2) & " where a.测量点=b.测量点"
- cnn.Execute SQL '不判断,更新可能存在的“测量点”
- '生成数据库不存在记录的SQL语句
- SQL = "select a.测量点" & AddFields & " from [Excel 12.0;Database=" & ActiveWorkbook.FullName & "].[Sheet1$" & Range("a9").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, "添加数据"
- End If
- '关闭连接释放内存
- rs.Close
- cnn.Close
- Set rs = Nothing
- Set cnn = Nothing
- Exit Sub
- errmsg:
- MsgBox Err.Description, , "错误报告"
- End Sub
复制代码 |
|