Object variable with or with block not set

前端 未结 2 547
谎友^
谎友^ 2021-01-27 03:07

I have xml file which I am trying to parse:

This is the xml file content



        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-27 03:38

    Your code ran fine for me. As @FlorentB. suggested, the document probably failed to parse. I suspect their is an error in the file name. Adding some error handling will help catch these errors.

    Sub PrintXML()
    
        Dim FilePath As String
        Dim XDoc As Object
    
        FilePath = ThisWorkbook.Path & "\test.xml"
    
        If Len(Dir(FilePath)) = 0 Then
            MsgBox "File not Found:" & vbCrLf & FilePath, vbCritical
            Exit Sub
        End If
    
        Set XDoc = CreateObject("MSXML2.DOMDocument")
        XDoc.async = False: XDoc.validateOnParse = False
        XDoc.Load ("C:\Users\norkiosk\Documents\Fax\test.xml")
    
        'Get Document Elements
        Set lists = XDoc.DocumentElement
    
        If lists Is Nothing Then
            MsgBox "Failed to Parse File:" & vbCrLf & FilePath, vbCritical
            Exit Sub
        End If
    
        'Traverse all elements 2 branches deep
        For Each listNode In lists.ChildNodes
            For Each fieldNode In listNode.ChildNodes
                Debug.Print "[" & fieldNode.BaseName & "] = [" & fieldNode.Text & "]"
            Next fieldNode
        Next listNode
    
        Set XDoc = Nothing
    
    End Sub
    

提交回复
热议问题