在 VBA 中深度复制或克隆 ADODB 记录集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25553594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:24:38  来源:igfitidea点击:

Deep Copy or Clone an ADODB recordset in VBA

excelvbaexcel-vbaadodbrecordset

提问by Ernesto Monroy

I have been searching for a way of duplicating or copying a recordset in VBA. And by that I mean, having the undelying data independent of each other.

我一直在寻找一种在 VBA 中复制或复制记录集的方法。我的意思是,使不可靠的数据相互独立。

I have tried

我试过了

Set copyRS = origRS.Clone
Set copyRS = origRS

When I use any of the methods I cant modify one recordset without modifying the other. So in this example:

当我使用任何一种方法时,我无法修改一个记录集而不修改另一个。所以在这个例子中:

  1. I create a recordset
  2. I populate the recordset with the name John
  3. I clone the recordset
  4. I modify the cloned one
  5. Check result
  1. 我创建了一个记录集
  2. 我用名字 John 填充记录集
  3. 我克隆记录集
  4. 我修改了克隆的
  5. 检查结果

Code:

代码:

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)

But unfortunately for me, this modifies both recordsets

但对我来说不幸的是,这会修改两个记录集

My question is:

我的问题是:

Is there a way of copying a recordset from another recordset and then modify the data independently of each other (without looping)?

有没有办法从另一个记录集中复制一个记录集,然后相互独立地修改数据(不循环)?

I know that evidently you can do it through a loop, but is there no other way?

我知道显然你可以通过循环来做到这一点,但没有其他方法吗?

回答by

++ Good question! btw. this way of copying object is called a deep copy.

++ 好问题!顺便提一句。这种复制对象的方式称为深拷贝

I usually get away with creating an ADODB.Streamand saving the current recordset into it.

我通常会创建一个ADODB.Stream并将当前记录集保存到其中。

Then you can use the .Open()method of a new recordset and pass the stream to it.

然后您可以使用.Open()新记录集的方法并将流传递给它。

For example:

例如:

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

Results as expected:

结果如预期:

enter image description here

在此处输入图片说明