VBA 每个循环都没有按我想要的方式循环

VBA For each loop not looping how i want

我有以下循环

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 似乎将自身重置回开始,因此它不是获取下一个 userbean,而是再次获取第一个,我如何修改下面的代码以获取节点中的下一个 userbean?

试试这个:

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