recordset.clone is not working

我修改了一段以前写的 vba,用到了 recordset.clone,没想到由于 vba 本身的 bug,克隆并没有进行,recordset.clone 返回值仍然是原记录集的引用。我在返回值记录集进行了 recordset.delete,结果把我原本想保持不动的原记录集里的记录给删了。

那个恨啊!实在没想到 recordset.clone 只引用不克隆,害我为恢复原记录折腾了很久。我没兴趣深究原因,就当是 vba bug,就算是我调用参数配置不当,recordset.clone 克隆不成功也不能随随便便返回一个值而不抛出错误。

既然 recordset.clone 不能用,找了一个前辈 Robert Gelb 写的函数来做真正的克隆。

Public Function Clone(ByVal oRs As ADODB.Recordset, _
    Optional ByVal LockType As ADODB.LockTypeEnum = adLockUnspecified) As ADODB.Recordset

    Dim oStream As ADODB.Stream
    Dim oRsClone As ADODB.Recordset

    'save the recordset to the stream object
    Set oStream = New ADODB.Stream
    oRs.Save oStream

    'and now open the stream object into a new recordset
    Set oRsClone = New ADODB.Recordset
    oRsClone.Open oStream, , , LockType

    'return the cloned recordset
    Set Clone = oRsClone

    'release the reference
    Set oRsClone = Nothing
End Function

Leave a Reply

Your email address will not be published. Required fields are marked *