Object variable with or with block not set

家住魔仙堡 提交于 2021-02-05 09:01:31

问题


I have xml file which I am trying to parse:

This is the xml file content

<MYSTUFF>
<COMPANYNAMES>
<COMPANYNAME>JUMPIN (JIMMY) LIMITED</COMPANYNAME>
<COMPANYNAME>BLADE RUNNER'S TRANSPORT</COMPANYNAME>
<COMPANYNAME>P Griffiths & Sons</COMPANYNAME>
<COMPANYNAME>SOMETIMES, NEVER</COMPANYNAME>
<COMPANYNAME>MASTER/CLASS</COMPANYNAME>
</COMPANYNAMES>
<FIRSTNAMES>
<FIRSTNAME>Richard</FIRSTNAME>
<FIRSTNAME>Jo & hn</FIRSTNAME>
<FIRSTNAME>Paul</FIRSTNAME>
<FIRSTNAME>Geo, rge</FIRSTNAME>
<FIRSTNAME>Ringo</FIRSTNAME>
</FIRSTNAMES>
<LASTNAMES>
<LASTNAME>Davies'</LASTNAME>
<LASTNAME>Lennon</LASTNAME>
<LASTNAME>McCartney(3)</LASTNAME>
<LASTNAME>Harrison</LASTNAME>
<LASTNAME>St/ar</LASTNAME>
</LASTNAMES>
</MYSTUFF>

This is the Code:

Dim XDoc As Object

Set XDoc = CreateObject("MSXML2.DOMDocument")
XDoc.async = False: XDoc.validateOnParse = False
XDoc.Load (ThisWorkbook.Path & "\test.xml")

'Get Document Elements
Set lists = XDoc.DocumentElement

'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

I am getting object variable with or with block not set on this line:

For Each listNode In lists.ChildNodes

回答1:


Your XML file doesn't load correctly.

a) I suppose your XML file starts with something like <?xml version="1.0" encoding="utf-8"?>, so that it can be identified as XML.

b) It's preferable to declare your object settings (always use Option Explicit in the declaration head). As you are using so called late binding, it's sufficient to write as follows:

Dim XDoc      As Object
Dim lists     As Object
Dim listNode  As Object
Dim fieldNode As Object

Hint If you set your XDoc object to memory with Set XDoc = CreateObject("MSXML2.DOMDocument") generally you are getting an older Version (3.0), so in most cases it's preferrable to use explicitly Set XDoc = CreateObject("MSXML2.DOMDocument.6.0") instead, which includes XPath automatically. If not you should complete your code as follows:

Set XDoc = CreateObject("MSXML2.DOMDocument")
XDoc.async = False: XDoc.validateOnParse = False
XDoc.setProperty "SelectionLanguage", "XPath"       ' << XPath functionality

c) Your XML file isn't loaded successfully because it contains a non readable character called ampersand ("&") within P Griffiths & Sons and Jo & hn, which has to be changed to "&#38;". The ampersand character is used as general prefix for special characters, so you can't be contained alone in the file. You can test loading with the following code instead of simply using XDoc.Load (ThisWorkbook.Path & "\test.xml"):

If XDoc.Load(ThisWorkbook.Path & "\test.xml") Then
   MsgBox "Loaded successfully"
Else
  Dim xPE        As Object    ' Set xPE = CreateObject("MSXML2.IXMLDOMParseError")
  Dim strErrText As String
  Set xPE = XDoc.parseError
  With xPE
     strErrText = "Load error " & .ErrorCode & " xml file " & vbCrLf & _
     Replace(.URL, "file:///", "") & vbCrLf & vbCrLf & _
    xPE.reason & _
    "Source Text: " & .srcText & vbCrLf & vbCrLf & _
    "Line No.:    " & .Line & vbCrLf & _
    "Line Pos.: " & .linepos & vbCrLf & _
    "File Pos.:  " & .filepos & vbCrLf & vbCrLf
  End With
  MsgBox strErrText, vbExclamation
  Set xPE = Nothing
  Exit Sub
End If

d) BTW, there are other and more complete ways to loop through your nodes (recursive calls). Sure you'll find some at the SO site.




回答2:


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


来源:https://stackoverflow.com/questions/46622752/object-variable-with-or-with-block-not-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!