Adding sum formula between every space ranges by vba

后端 未结 2 707
逝去的感伤
逝去的感伤 2021-01-28 14:48

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 usin

相关标签:
2条回答
  • 2021-01-28 15:12

    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".

    0 讨论(0)
  • 2021-01-28 15:37

    Without VBA:

    Say we have data in column A like:

    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:

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

    0 讨论(0)
提交回复
热议问题