Adding sum formula between every space ranges by v

2020-05-06 12:38发布

I was trying to do an automation and i was stuck here, where i need to add sum formula dynamically in between the space ranges. I'm completely lost here for adding formula using VBA can anyone help me out.

enter image description here

Thank you in advance :)

2条回答
Bombasti
2楼-- · 2020-05-06 13:29

I'm assuming what you want is if there is a blank in a cell, you want all of the other elements summed and the result placed in that blank. There are probably any number of ways to code this, but here is my attempt

Sub formulateSubtotals()
finalRow = Cells(Worksheets("Sheet1").Rows.Count, 1).End(xlUp).Row
finalCol = Cells(1, Worksheets("Sheet1").Columns.Count).End(xlToLeft).Column
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
End Sub

This also assumes that the sheet in question is entitled "Sheet1".

查看更多
Animai°情兽
3楼-- · 2020-05-06 13:39

Without VBA:

Say we have data in column A like:

enter image description here

and we want to calculate of sum of each of the blocks separated by a blank cell. In B2 enter:

=IF(A2<>"","",SUM($A$1:A2)-SUM($B$1:B1))

and copy down:

enter image description here

If this is of no value, I will delete the answer.

查看更多
登录 后发表回答