如何在“对于每个循环”中进行偏移

时间:2019-09-27 20:14:37

标签: excel vba

在嵌套循环中,我试图弄清楚如何指示结果应该在数组中第二个和第三个工作表的不同列中显示。对于数组中的第一个工作表,一切都很好。对于第二个和第三个工作表,我需要将结果放在下一列中。我只是不确定该在哪里说,以免弄乱循环的“嵌套”部分。

我为自己编写一个嵌套循环直到无法工作感到非常自豪。最终,我意识到它在技术上是可行的,但是循环又一次又一次地替换了同一列的相同单元格,因为我没有指定结果应该越过一列。我发现这个answer about offsetting看起来很有前途,但是有点烦人。

Dim SG As Worksheet, SG2017 As Worksheet, SG2018 As Worksheet, SG2019 As Worksheet
    Set SG = Workbooks("Subgroup Summary Template").Sheets("SG")
    Set SG2017 = Workbooks("2017 Subgroup Summary").Sheets("2017")
    Set SG2018 = Workbooks("2018 Subgroup Summary").Sheets("2018")
    Set SG2019 = Workbooks("2019 Subgroup Summary").Sheets("2019")
Dim SGdata As Variant
Dim CurrentSGdata As Variant
    SGdata = Array(SG2017, SG2018, SG2019)
Dim i As Long

'ALL STUDENTS
For Each CurrentSGdata In SGdata
    With CurrentSGdata.Range("A1")
         For i = 3 To 8
         .AutoFilter Field:=7, Criteria1:=i
         .AutoFilter Field:=8, Criteria1:="Total Population"
         .AutoFilter Field:=1, Criteria1:=school
                SG.Cells(i, 3) = CurrentSGdata.UsedRange.SpecialCells(xlCellTypeVisible).Areas(2).Columns(15).Cells(1, 1)
                    On Error Resume Next
                SG.Cells(i, 6) = CurrentSGdata.UsedRange.SpecialCells(xlCellTypeVisible).Areas(2).Columns(17).Cells(1, 1)
                    On Error Resume Next
            CurrentSGdata.AutoFilterMode = False
         Next i
Next CurrentSGdata

例如,如何指示在"CurrentSGdata,"的第二次迭代中,SG.Cells(i,3)应该变成SG.Cells(i,4)

1 个答案:

答案 0 :(得分:2)

例如:

Dim i As Long, n As Long

'ALL STUDENTS
n = 3
For Each CurrentSGdata In SGdata
    With CurrentSGdata.Range("A1")
         For i = 3 To 8
             .AutoFilter Field:=7, Criteria1:=i
             .AutoFilter Field:=8, Criteria1:="Total Population"
             .AutoFilter Field:=1, Criteria1:=school

             On Error Resume Next

             SG.Cells(i, n) = CurrentSGdata.UsedRange.SpecialCells(xlCellTypeVisible) _
                                .Areas(2).Columns(15).Cells(1, 1)

             SG.Cells(i, 6) = CurrentSGdata.UsedRange.SpecialCells(xlCellTypeVisible) _
                                .Areas(2).Columns(17).Cells(1, 1)

             On Error Goto 0 '<< stop ignoring errors

             CurrentSGdata.AutoFilterMode = False
         Next i
     End With 'missing in your code?
     n = n + 1
Next CurrentSGdata