在VBA中深度复制或克隆ADODBlogging集
我一直在寻找一种在VBA中复制或复制logging集的方法。 而我的意思是,让未确定的数据彼此独立。
我努力了
Set copyRS = origRS.Clone Set copyRS = origRS
当我使用任何方法时,我无法修改一个logging集而不修改其他logging集。 所以在这个例子中:
- 我创build一个logging集
- 我用John来填充logging集
- 我克隆logging集
- 我修改了克隆的
- 检查结果
码:
Dim origRS As Recordset, copyRS As Recordset Set origRS = New Recordset 'Create field origRS.Fields.Append "Name", adChar, 10, adFldUpdatable origRS.Open 'Add name origRS.AddNew "Name", "John" 'Clone/copy Set copyRS = origRS.Clone 'Change record in cloned/copied recordset copyRS.MoveFirst copyRS!Name = "James" 'This should give me "JamesJohn" MsgBox copyRS.Fields(0).Value & origRS.Fields(0)
但不幸的是,这个修改了两个logging集
我的问题是:
有没有办法从另一个logging集复制logging集,然后相互独立地修改数据(没有循环)?
我知道,显然你可以通过循环做到这一点,但没有其他的办法吗?
++好问题! 顺便说一句。 这种拷贝对象的方式称为深拷贝 。
我通常会创build一个ADODB.Stream
并保存当前logging集。
然后,您可以使用新logging集的.Open()
方法并将stream传递给它。
例如:
Sub Main() Dim rs As ADODB.Recordset Set rs = New ADODB.Recordset rs.Fields.Append "Name", adChar, 10, adFldUpdatable rs.Open rs.AddNew "Name", "John" Dim strm As ADODB.Stream Set strm = New ADODB.Stream rs.Save strm Dim copy As New ADODB.Recordset copy.Open strm copy!Name = "hellow" Debug.Print "orignal recordset: " & rs.Fields(0).Value Debug.Print "copied recordset: " & copy.Fields(0).Value strm.Close rs.Close copy.Close Set strm = Nothing Set rs = Nothing Set copy = Nothing End Sub
结果如预期: