You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从XML提取嵌套数据到Excel时遇Run-time error 91问题求助

XML解析VBA报错Run-time error 91求助

我正在尝试解析XML文件,提取其中的Status和DisclaimReason(简称DR)数据到Excel表格中。运行VBA代码时触发Run-time error 91:对象变量或With块变量未设置,报错代码行如下:
Sheets("Sheet1").Cells(i, 4).Value = xmlfda.getElementsByTagName("Status")(0).Text

完整VBA代码

Sub PullComplexXML()

    Dim xmlDoc As Object
    Dim XMLPGA As Object
    Dim xmlfda As Object
    Dim i As Integer        
        
    'Dim xmlDoc As Object
    Set xmlDoc = CreateObject("MSXML2.DOMDocument")
    xmlDoc.Load ("C:\books.xml")

    ' Adjust "SectionName"
    Dim sectionNode As Object
    Set sectionNode = xmlDoc.SelectSingleNode("//PGAs")

    If Not sectionNode Is Nothing Then
        Dim childNode As Object
        For Each childNode In sectionNode.ChildNodes
            Debug.Print childNode.Text
        Next childNode
    Else
        MsgBox "Section not found"
    End If

    'Pull nested data

     ' Create a new XML Document object
     Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0")

        ' Configure properties
        xmlDoc.async = False
        xmlDoc.validateOnParse = False

        ' Load the XML file
        If Not xmlDoc.Load("C:\books.xml") Then
            MsgBox "Failed to load XML file. Exiting."
            Exit Sub
        End If

        i = 2
        'Loop through each PGA
         For Each XMLPGA In xmlDoc.DocumentElement.ChildNodes
            
            'Loop through each FDA             
             For Each xmlfda In XMLPGA.ChildNodes
                Sheets("Sheet1").Cells(i, 1).Value = xmlDoc.DocumentElement.getAttribute("Product") 'Product
                Sheets("Sheet1").Cells(i, 2).Value = XMLPGA.getAttribute("PGAs") ' PGA
                Sheets("Sheet1").Cells(i, 3).Value = xmlfda.getAttribute("FDA") ' FDA
                
                Sheets("Sheet1").Cells(i, 4).Value = xmlfda.getElementsByTagName("Status")(0).Text '  Status
                Sheets("Sheet1").Cells(i, 5).Value = xmlfda.getElementsByTagName("DisclaimReason")(0).Text ' DR
                            
                i = i + 1
            Next xmlfda
        Next XMLPGA

        Set xmlDoc = Nothing
        MsgBox "Data loaded. Now validate your file!"
End Sub

待解析XML结构

  • 根节点包含Product属性
  • 根节点下存在多个带PGAs属性的PGA节点
  • 每个PGA节点下有多个带FDA属性的FDA节点
  • 每个FDA节点下包含Status和DisclaimReason子节点

内容的提问来源于stack exchange,提问作者jackie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 06:03:10