无法在EXCEL VBA中更新ADO记录集

jm81lzqq  于 2022-11-18  发布在  其他
关注(0)|答案(2)|浏览(274)

我正在创建一个使用excel range作为数据源的记录集。代码是

Sub Hello()

    Dim xlXML             As Object
    Dim adoRecordset      As Object
    Dim rng               As Range

    Set rng = Range("A1:C6")
    Set adoRecordset = CreateObject("ADODB.Recordset")
    Set xlXML = CreateObject("MSXML2.DOMDocument")
    xlXML.LoadXML rng.Value(xlRangeValueMSPersistXML)
    adoRecordset.CursorLocation = 3
    adoRecordset.Open xlXML, CursorType:=2, LockType:=3

    adoRecordset.Movefirst

    adoRecordset.Fields(1) = 1000 'this is the error line
    adoRecordset.Update

    Set adoRecordset = Nothing
    Set xlXML = Nothing

    End Sub

我无法更新数据集,得到错误“多步操作生成错误。检查每个值(-2147217887)"。我不知道我哪里出错了。我使用的是Excel 2007。

zynd9foi

zynd9foi1#

我认为在记录集中添加新行或编辑现有行之前,必须输入:

adoRecordset.Edit
' OR
adoRecordset.AddNew
wwodge7n

wwodge7n2#

其根本原因是,从Range派生的RecordSet在默认情况下是不可变的--正如Andrew here在文章中所指出的那样。
假定源区域具有这些内容(以消除“数据类型”问题)
| | A级|B| C语言|
| - -|- -|- -|- -|
| 一个|$A$1| $B$1| $C$1|
| 2个|$A$2| $B$2| $C$2|
| 三个|$A$3美元|$B$3| $C$3|
| 四个|$A$4| $B$4| $C$4|
| 五个|$A$5| $B$5| $C$5|
| 六个|$A$6| $B$6| $C$6|
那么OP代码的工作版本将是

Sub Hello()

    Dim xlXML             As Object
    Dim ElementNode       As Object
    Dim AttributeNodes    As Object
    Dim Child             As Object
    Dim adoRecordset      As Object
    Dim rng               As Range

    Set rng = Range("A1:C6")
    Set adoRecordset = CreateObject("ADODB.Recordset")
    Set xlXML = CreateObject("MSXML2.DOMDocument")
    
    xlXML.LoadXML rng.Value(xlRangeValueMSPersistXML)
    xlXML.SetProperty "SelectionNamespaces", "xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'"
    
    Set ElementNode = xlXML.SelectSingleNode("xml/x:PivotCache/s:Schema/s:ElementType")
    ElementNode.setAttribute "rs:updatable", "true"
    
    Set AttributeNodes = xlXML.SelectNodes("xml/x:PivotCache/s:Schema/s:AttributeType")
    For Each Child In AttributeNodes
        Child.setAttribute "rs:write", "true"
    Next Child
        
    adoRecordset.CursorLocation = 3
    adoRecordset.Open xlXML, CursorType:=2, LockType:=3

    adoRecordset.Movefirst

    adoRecordset.Fields(1) = 1000
    adoRecordset.Update

    Range("A1").CopyFromRecordset adoRecordset    'added to reflect the update on the worksheet
    Set adoRecordset = Nothing
    Set xlXML = Nothing

End Sub

相关问题