VBA对于每个循环没有循环我想要的方式

时间:2016-03-05 20:34:13

标签: vba foreach nodevalue

我有以下循环

r = 4
c = 4

Set userBeanList = XMLDOC.SelectNodes("/response/responseBody/responseList/item[recordType='TPI']/*[not(self::catch or self::reprive or self::cate or self::reet or self::aarg or self::crane)]")
For a_counter = 1 To 7
For Each userbean In userBeanList

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

Sheets("Sheet2").Cells(r + 1, c) = userbean.Text
 r = r + 2
a_counter = a_counter + 1
If (a_counter = 7) Then Exit For

Next userbean
c = c + 1
r = 4
a_counter = 1
Next a_counter

基本上遍历我的节点打印第4行中的节点名称,然后是第5行下面的单元格中的节点值,这会重复6次,以便我获得节点名称,后跟电子表格列表中的节点值。然后我有一个计数器,当它达到7个出口时,for循环将该列递增1,将该行重置为4并重复此过程。然而,userBeanList中的For Each userbean似乎将自身重置为start,所以不是获取下一个userbean,而是再次获取第一个,我如何修改下面的代码以获取节点中的下一个userbean?

1 个答案:

答案 0 :(得分:3)

试试这个:

r = 4
c = 4
a_counter = 1

Set userBeanList = XMLDOC.SelectNodes("/response/responseBody/responseList/item[recordType='TPI']/*[not(self::catch or self::reprive or self::cate or self::reet or self::aarg or self::crane)]")

For Each userbean In userBeanList
    Sheets("Sheet2").Cells(r, c) = userbean.nodeName
    Sheets("Sheet2").Cells(r + 1, c) = userbean.Text
    r = r + 2
    a_counter = a_counter + 1
    If a_counter  >= 7 Then
        c = c + 1
        r = 4
        a_counter = 1
    End If

Next userbean

您正在尝试将a_counter用作for循环,并且作为一个单独的计数器,您不需要它会阻碍的for循环。

修改

你根本不需要a-Counter。您可以使用r值来检查6完成时间:

r = 4
c = 4

Set userBeanList = XMLDOC.SelectNodes("/response/responseBody/responseList/item[recordType='TPI']/*[not(self::catch or self::reprive or self::cate or self::reet or self::aarg or self::crane)]")

For Each userbean In userBeanList
    Sheets("Sheet2").Cells(r, c) = userbean.nodeName
    Sheets("Sheet2").Cells(r + 1, c) = userbean.Text
    r = r + 2
    If r  > 14 Then
        c = c + 1
        r = 4
    End If

Next userbean