Using Sum Function in VBA

leocar28

New Member
Joined
Mar 1, 2021
Messages
3
Office Version
  1. 365
Platform
  1. Windows
Hi,

I have a small code that pastes in a formula to sum the cell through to P2 as long as there is a valve in the current cell. It loops for all values in the array. It works fine but instead of pasting the formula, is there a way of completing the sum function in VBA and only pasting the calculated value? Essentially it is creating a cumulative tally in column Q of the values in column P only if there is a value in column P. In the code startrow begins at 2 and loops with the total row count in the sheet

If Cells(startrow, "P") <> "" Then
Cells(startrow, "Q").Formula = "=SUM(P2:P" & startrow & ")"
End If

Cheers
 

Excel Facts

Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.
VBA Code:
Sub Running_Totals()
    Dim v As Variant, i As Long, tot As Double
    With Range("P2", Range("P" & Rows.Count).End(xlUp))
        v = .Value
        For i = 1 To UBound(v)
            If v(i, 1) <> "" Then
                tot = tot + v(i, 1)
                v(i, 1) = tot
            End If
        Next i
        .Offset(0, 1).Value = v
    End With
End Sub
 
Upvote 0
How about to use Application.Sum(range())
For example in your code:

VBA Code:
If Cells(startrow, "P") <> "" Then
Cells(startrow, "Q")=APPLICATION.SUM(Range("P2:P" & startrow ))
End If
 
Upvote 0
Cells(startrow, "Q")=APPLICATION.SUM(Range(P2:P" & startrow & ")")
I was after something simple like that but I keep getting a compile error.
1614649946918.png
 
Upvote 0
Hi, I have updated the code as follow:
Cells(startrow, "Q")=APPLICATION.SUM(Range("P2:P" & startrow ))
I forgot to revise your .formula code in details.
Perfect, thanks.
 
Upvote 0

Forum statistics

Threads
1,214,393
Messages
6,119,261
Members
448,880
Latest member
aveternik

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top