如何使用非连续的嵌套循环

时间:2015-04-21 15:03:12

标签: excel vba excel-vba

以下是我正在使用的代码片段。我有一个问题,我需要如何命名j。我需要它为3,4,5,6为第一个tab_name然后7,8,9,10为下一个和11,12,13,14为那之后的那个等。

我可以改进下面的尝试方式吗?

tab_names = Array("11EB", "11WB", "12EB", "12WB", "13EB", "13WB", "14EB")
Location = Array(3, 7, 11)

For Each indiv_tab In tab_names
    For Each j In Location
        For i = 9 To 24
            Sheets("Front Page").Cells(2, 2) = Cells(i, 1)
            Cells(i, j) = Sheets(indiv_tab).Cells(2993, 9)
            Cells(i, j + 1) = Sheets(indiv_tab).Cells(2993, 22)
            Cells(i, j + 2) = Sheets(indiv_tab).Cells(2993, 35)
            Cells(i, j + 3) = Sheets(indiv_tab).Cells(2993, 48)
        Next i
    Next j
Next

修改

我现在使用下面的代码,但是,我需要它同时使用Next tab_name和Next j。反正有吗?

tab_names = Array("11EB", "11WB", "12EB", "12WB", "13EB", "13WB", "14EB", "14WB", "15NB", "15SB", "16NB", "16SB", "17EB", "17WB", "18EB", "18WB", "19NB", "19SB", "20NB", "20SB", "21NB", "21SB", "22NB", "22SB", "23NB", "23SB", "24NB", "24SB", "25NB", "25SB", "26NB", "26SB", "27EB", "27WB", "28EB", "28WB", "29EB", "29WB", "30EB", "30WB", "31NB", "31SB", "32NB", "32SB", "33EB", "33WB", "34EB", "34WB", "35NB", "35SB", "36NB", "36SB", "37EB", "37WB", "38NB", "38SB", "39NB", "39SB", "40EB", "40WB", "41EB", "41WB", "A12NB", "A12SB", "M11NB", "M11SB", "M25NB", "M25SB", "A120EB", "A120WB", "A120AEB", "A120AWB")
   For i = 9 To 24
    For Each indiv_tab In tab_names
     For j = 3 To 291 Step 4

            Sheets("Front Page").Cells(2, 2) = Cells(i, 1)

            Cells(i, j) = Sheets(indiv_tab).Cells(2993, 9)
            Cells(i, j + 1) = Sheets(indiv_tab).Cells(2993, 22)
            Cells(i, j + 2) = Sheets(indiv_tab).Cells(2993, 35)
            Cells(i, j + 3) = Sheets(indiv_tab).Cells(2993, 48)
      Next j
    Next
  Next i

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

你是说你希望j在第一个标签上迭代3,4,5,6,然后在第二个选项卡上迭代7,8,9,10 ......?

如果是这样,以下情况应该有效。从我指定的位置开始(如果您在其他地方使用它,则声明为新变量),然后每次手动调整它。

tab_names = Array("11EB", "11WB", "12EB", "12WB", "13EB", "13WB", "14EB")
Location = Array(3, 4, 5, 6) '##changed this

For Each indiv_tab In tab_names
    For Each j In Location
        For i = 9 To 10
            Sheets("Front Page").Cells(2, 2) = Cells(i, 1)
            Cells(i, j) = Sheets(indiv_tab).Cells(2993, 9)
            Cells(i, j + 1) = Sheets(indiv_tab).Cells(2993, 22)
            Cells(i, j + 2) = Sheets(indiv_tab).Cells(2993, 35)
            Cells(i, j + 3) = Sheets(indiv_tab).Cells(2993, 48)
        Next i
    Next j

    'adjust values on each loop
    For i = 0 To UBound(Location, 1)
        Location(i) = Location(i) + 4
    Next i

Next