***编辑7/19 @AcsErno求和的公式工作正常,但是由于有8行,因此它在每个空白行中输入和。是否可以在代码中输入多个公式?
我尝试复制公式(Cells(LastRow + 2,j).FormulaLocal ...)并将+1更改为+2(依此类推),但只有第一行空白求和了,其他则等于或等于其上方的行。
'sum inbetween blanks
finalRow = Cells(Worksheets("page1").Rows.Count, 1).End(xlUp).Row
For Each j In Array(12, 13, 14) 'original: For j = 1 To finalCol
For i = finalRow + 1 To 1 Step -1
If IsEmpty(Cells(i, j)) Then
If IsEmpty(Cells(i - 2, j)) Then
firstrow = i - 1
LastRow = firstrow
Else
LastRow = i - 1
firstrow = Cells(i - 1, j).End(xlUp).Row
End If
Cells(LastRow + 1, j).FormulaLocal = _
"= sum(" & Range(Cells(firstrow, j), Cells(LastRow, j)).Address(False, False) & ")"
Cells(LastRow + 2, j).FormulaLocal = _
"= sum(" & Range(Cells(firstrow, j), Cells(LastRow, j)).Address(False, False) & ")"
End If
Next i
Next j
Application.ScreenUpdating = True
如果有帮助,下面是一些我要使用的公式:
=SUMIF(P138:P158,"<>*Hold*",L138:L158)
=SUM(SUMIF(H5:H21,{"China"},L5:L21))
=SUM(SUMIF(H5:H21,{"Other"},L5:L21))
=SUM(SUMIF(O12:O28,{"*H1*"},L12:L28))
=SUM(SUMIF(O12:O28,{"H2","H2-PRESSED"},L12:L28))
Link to Sum Code Link to Enter Blank Rows
对于每个不同的星期数,我的数据都用8个空白行分隔开来,每个数字有8个空白行。我需要在每个星期内/空白之间插入汇总特定事物的公式。
行数将是动态的,因此公式也必须是动态的。我用来求和的唯一代码只有在中间有1个空白行(而不是8个)的情况下才能很好地工作,而且我不确定如何向其中添加更多行/公式。
Here is what the excel looks like (shortened version)
Here is what I'm trying to make it look like
'insert blank columns based on change in wk
Dim X As Long, LastRow As Long
Const DataCol As String = "A"
Const StartRow = 2
LastRow = Cells(Rows.Count, DataCol).End(xlUp).Row
For X = LastRow To StartRow + 1 Step -1
If Cells(X, DataCol).Value <> Cells(X - 1, DataCol) Then Rows(X).Resize(8).Insert
Next
finalRow = Cells(Worksheets("page1").Rows.Count, 1).End(xlUp).Row
finalCol = Cells(1, Worksheets("page1").Columns.Count).End(xlToLeft).Column
For j = 12 To 14 'original: For j = 1 To finalCol
For i = finalRow + 1 To 1 Step -1
If IsEmpty(Cells(i, j)) Then
If IsEmpty(Cells(i - 2, j)) Then
firstrow = i - 1
LastRow = firstrow
Else
LastRow = i - 1
firstrow = Cells(i - 1, j).End(xlUp).Row
End If
Cells(i, j) = Application.WorksheetFunction.Sum(Range(Cells(firstrow, j), Cells(LastRow, j)))
End If
Next i
Next j
答案 0 :(得分:0)
目前尚不清楚为什么要在每个循环中更改第一行。另外,为什么要覆盖列中的原始值。如果您有静态表格,并且想在其下汇总一列,则只需标识第一行和最后一行(如您所正确操作),然后
Cells(LastRow + 1, j) = Application.WorksheetFunction.Sum(Range(Cells(firstrow, j), Cells(LastRow, j)))
或者您可以插入公式
Cells(LastRow + 1, j).FormulaLocal = _
"=sum(" & Range(Cells(firstrow, j), Cells(LastRow, j)).Address(False, False) & ")"
您也可以考虑SUMIF
仅添加H1和H2类别。
也不清楚为什么要汇总字符串列。这没有道理。您知道数字列的确切位置,因此可以指定列号。我建议选择1:
For j = 6 To 8
或选项2:
For Each j in Array (6,7,8) ' it is more flexible