|
楼主 |
发表于 2014-6-2 17:12
|
显示全部楼层
本帖最后由 zhcshine 于 2014-6-2 17:19 编辑
zhaogang1960 发表于 2014-5-13 17:27
链接表不能、也不需要修改,因为它就是你链接的那个工作表的“镜子”,工作表修改后,链接表也当然的显示 ... 新问题: 参照“根据工作表批量更新数据库并向数据库添加不存在的记录(不使用循环)2007”帖子内容 - Private Sub CommandButton1_Click()
- '引用Microsoft ActiveX Data Objects 2.x Library
- 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
- Shell "net use \\ZHC20120268\data /USER:ZHC20120268 shareuser"
-
- myPath = "\\ZHC20120268\data\data1.accdb"
- myTable = "pla_data"
- On Error GoTo errmsg
- cnn.Open "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" & myPath '连接数据库
-
- arrFields = Range("A2:AE2") '工作表中的字段名写入数组
-
- '生成更新字符串,如:a.姓名=b.姓名,a.性别=b.性别,……
- For i = 2 To UBound(arrFields, 2)
- strTemp = strTemp & ",a." & arrFields(1, i) & "=b." & arrFields(1, i)
- Next
-
- SQL = "select a.* from [Excel 12.0;Database=" & ActiveWorkbook.FullName & "].[Sheet2$" & Range("a2").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
- Exit Sub
- errmsg:
- MsgBox Err.Description, , "错误报告"
- End Sub
复制代码 测试插入新记录SQL语句可以通过
- Private Sub CommandButton2_Click()
- 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
- Shell "net use \\ZHC20120268\data /USER:ZHC20120268 shareuser"
- myPath = "\\ZHC20120268\data\data1.accdb"
- myTable = "pla_data"
- On Error GoTo errmsg
- cnn.Open "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" & myPath '连接数据库
-
- arrFields = Range("A2:AE2") '工作表中的字段名写入数组
-
- '生成更新字符串,如: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 & "].[Sheet2$" _
- & Range("a2").CurrentRegion.Address(0, 0) & "] b set " & Mid(strTemp, 2) & " where a.包被码=b.包被码"
- cnn.Execute SQL
-
- 'Set rs = New ADODB.Recordset
- rs.Open SQL, cnn, adOpenKeyset, adLockOptimistic
- '
- '插入数据库不存在记录
- If rs.RecordCount > 0 Then '如果工作表中含有数据库不存在记录
-
- MsgBox rs.RecordCount & "行数据已经更新到数据库!", vbInformation, "更新数据"
- Else
- MsgBox "工作表的数据数据库中已经存在。", vbInformation, "添加数据失败"
- End If
-
- '关闭连接释放内存
- rs.Close
- cnn.Close
- Set rs = Nothing
- Set cnn = Nothing
- Exit Sub
- errmsg:
- MsgBox Err.Description, , "错误报告"
- End Sub
复制代码 生成更新SQL语句 却提示对象关闭时,不允许操作,这是为什么?
|
|