【发布时间】:2019-07-19 00:42:54
【问题描述】:
*** 编辑 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
【问题讨论】: