在Excel中横跨水平数据库的嵌套循环

在这里输入图像说明 嗨,我有一个数据库有91列,每列有行8至21(固定)。 91列包含部门标题,行内容取决于部门标题。 列以交替的方式进行,其中第1部分在C列,第2部分在E列,并且所有91列都遵循该模式。 我想为给定的公式"=SUMIFS('L4 - Data Sheet'!$Q:$Q,'L4 - Data Sheet'!$R:$R,'WF - L4'!BY$5,'L4 - Data Sheet'!$P:$P,$A8,'L4 - Data Sheet'!$A:$A,'WF - L4'!$A$3)"使用嵌套循环,但似乎不起作用,我也不清楚如何去做。 因为硬编码91列列与每列的各行范围是非常繁琐的工作:/这是我目前工作的硬代码我做的。

 Sub WFCorp4() With Sheets("WF - L4 (2)") '91 columns * 2 because there is two different subsectors qty and direct assigned space '.Range("BY8:BY21").Formula = "=SUMIFS('L4 - Data Sheet'!$Q:$Q,'L4 - Data Sheet'!$R:$R,'WF - L4'!BY$5,'L4 - Data Sheet'!$P:$P,$A8,'L4 - Data Sheet'!$A:$A,'WF - L4'!$A$3)" '.Range("CA8:CA21").Formula = "=SUMIFS('L4 - Data Sheet'!$Q:$Q,'L4 - Data Sheet'!$R:$R,'WF - L4'!CA$5,'L4 - Data Sheet'!$P:$P,$A8,'L4 - Data Sheet'!$A:$A,'WF - L4'!$A$3)" '.Range("CN8:CN21").Formula = "=SUMIFS('L4 - Data Sheet'!$U:$U,'L4 - Data Sheet'!$R:$R,'WF - L4'!CM$5,'L4 - Data Sheet'!$P:$P,$A8,'L4 - Data Sheet'!$A:$A,'WF - L4'!$A$3)" End With End Sub 

这是我为工作表尝试的嵌套循环代码。

 Sub ShortcutWFCorp4() Dim lastcol As Long Dim lastrow As Long lastcol = Cells(8, Columns.Count).End(xlToLeft).Column lastrow = Cells(21, "C").End(xlUp).Row Dim i As Long Dim j As Long For i = i + 2 To lastcol For j = 8 To lastrow Sheets("WF - L4 (2)").Cells(i, j).Range.FormulaR1C1 = "=SUMIFS('L4 - Data Sheet'!R4C17:R132C17,'L4 - Data Sheet'!R4C18:R132C18,'WF - L4 (2)'!i,'L4 - Data Sheet'!R4C16:R132C16,'L4 - Data Sheet'R4C1,R132C1,'WF - L4(2)'!R3C1)" Next Next End Sub 

希望有人能帮助! 谢谢

附上的是它大致看起来像的形象。 每个单元格都有我的问题中提到的公式。 我想使用嵌套循环来自动化列表输出在数量列! 部门以另一种顺序进行。

我认为我从你提供的那个中破译了你的公式。 devise良好的公式不需要嵌套循环; 简单地把它像一个填充下来一次放入所有的细胞。

 Option Explicit Sub ShortcutWFCorp4() Dim i As Long, j As Long 'cannot use lastrow until there is something in column C Dim lastCol As Long ', lastRow As Long With Worksheets("WF - L4 (2)") '<~~ define it ONCE here 'you want to put formulas into all the columns with QTY in row 7 lastCol = .Cells(7, Columns.Count).End(xlToLeft).Column 'I guess column C is the left-most in your image but you canot 'get last row list this until there is something in it 'I'll use 21 'lastrow = .Cells(21, "C").End(xlUp).Row 'columns 3, 5, 7, etc For i = 3 To lastCol Step 2 '"=SUMIFS('L4 - Data Sheet'!$Q:$Q, ' 'L4 - Data Sheet'!$R:$R, 'WF - L4'!BY$5, ' 'L4 - Data Sheet'!$P:$P, $A8, ' 'L4 - Data Sheet'!$A:$A, 'WF - L4'!$A$3) .Range(.Cells(8, i), .Cells(21, i)).FormulaR1C1 = _ "=SUMIFS('L4 - Data Sheet'!C17, " & _ "'L4 - Data Sheet'!C18, R5C" & 74 + i & ", " & _ "'L4 - Data Sheet'!C16, RC1, " & _ "'L4 - Data Sheet'!C1, R3C1)" Next i End With End Sub 

我猜想,第一个数字是在C7。 你说公式是进入第8-21行。 如果C列中没有东西到第21行,那么寻找“最后一行”是没有意义的,所以我硬编码了第8行到第21行。