将每个循环更改为for循环

时间:2016-03-03 22:47:43

标签: vba loops for-loop

我在VBA中有以下代码

Dim userBeanList As MSXML2.IXMLDOMNodeList
Dim userbean As MSXML2.IXMLDOMNode
Dim beanChild As MSXML2.IXMLDOMNode

XMLDOC.Load ("https://www.catch.api")

r = 4
Set userBeanList = XMLDOC.SelectNodes("/response/responseBody/responseList/item[recordType='TPI']")
For Each userbean In userBeanList
    For Each beanChild In userbean.ChildNodes
    If beanChild.nodeName = "catch" Then GoTo NextIteration

       Sheets("Sheet2").Cells(r, 1) = beanChild.nodeName
         Sheets("Sheet2").Cells(r, 2) = beanChild.Text

  r = r + 1
NextIteration:
    Next beanChild
Next userbean

目前我循环遍历所有节点,然后在这种情况下忽略名为“catch”的节点,然后进入下一次迭代,因为我不需要该节点或节点值。 我不会这样做,而是将我的循环更改为可以直接转到感兴趣的节点的循环,因此不必跳过看起来效率低下的迭代?

/////在parfait的帮助下

Dim userBeanList As MSXML2.IXMLDOMNodeList
Dim userbean As MSXML2.IXMLDOMNode
Dim beanChild As MSXML2.IXMLDOMNode

XMLDOC.Load ("http://www.catch.api")

r = 4

Set userBeanList = XMLDOC.SelectNodes("/response/responseBody/responseList/item[recordType='TPI']/*[not(local-name)='catch']")
For Each userbean In userBeanList

       Sheets("Sheet2").Cells(r, 1) = userbean.nodeName

         Sheets("Sheet2").Cells(r, 2) = userbean.Text

         r = r + 1

Next userbean

1 个答案:

答案 0 :(得分:1)

考虑将其从xpath表达式中排除。以下指定name()local-name()不等于' catch'的所有儿童。这甚至可以避免子节点上的内部For Each循环。

Set userBeanList = XMLDOC.SelectNodes("/response/responseBody/responseList" _
                                     & "/item[recordType='TPI']/*[not(local-name)='catch']")

或者,使用self

Set userBeanList = XMLDOC.SelectNodes("/response/responseBody/responseList" _
                                     & "/item[recordType='TPI']/*[not(self::catch)]")