VBA:嵌套For / Loop

时间:2016-09-07 17:50:52

标签: vba for-loop

我正在创建一个宏,它将所有数据从一个工作簿/多个工作表复制到另一个工作簿/多个工作表中。第一个电子表格有7个名为Sun-Sat的工作表。第二个工作表有10个工作表,3个工作表无关紧要,其他7个工作表命名为周日 - 周六。

我分别测试了每个for循环,它们根据需要工作。当尝试组合它们时,内部for语句重复并在退出之前循环所有日期。我已经尝试合并一个退出来跳出内部但是当回到内部时它不会增加+1以进入下一个日期。有没有一种简单的方法可以从外部for语句中添加+1?

enter code here
Dim wsShortDays, wsFullDays As Variant
Dim wsShortDaysCrnt, wsFullDaysCrnt As Long
Dim SD, FD As Long

wsShortDays = Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
wsFullDays = Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")

For FD = LBound(wsFullDays) To UBound(wsFullDays)
    With wbk1.Worksheets(wsFullDays(FD))

        For SD = LBound(wsShortDays) To UBound(wsShortDays)
            With wbk2.Worksheets(wsShortDays(SD))
                wbk2.Worksheets(wsShortDays(SD)).Activate
                Range("A:H").Copy
            End With
            Exit For
        Next SD


        wbk1.Worksheets(wsFullDays(FD)).Activate
        Range("C:J").PasteSpecial xlPasteAllUsingSourceTheme
        SD = 1
    End With
Next FD

1 个答案:

答案 0 :(得分:2)

您不需要内部循环,因为您的数组已同步,只需使用第一个循环中的相同参考编号。它会将Sunday等同于Sun,依此类推:

Dim wsShortDays As Variant, wsFullDays As Variant
Dim FD As Long

wsShortDays = Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
wsFullDays = Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")

For FD = LBound(wsFullDays) To UBound(wsFullDays)
   wbk2.Worksheets(wsShortDays(FD)).Range("A:H").Copy
   wbk1.Worksheets(wsFullDays(FD)).Range("C:J").PasteSpecial xlPasteAllUsingSourceTheme
Next FD