Dynamically Sum a column

Ian Bertie

New Member
Joined
Jul 10, 2010
Messages
21
Good afternoon Guru's

I am trying to dynamically sum a column (code below), however I am getting an error due to the cells having a formula (example: =IF(H47<>"",G47*H47,""))

Private Sub CommandButton1_Click()

lastrow = Worksheets("Invoice").Cells(Rows.Count, 9).End(xlUp).Row
Dim a As Integer
a = 0

For b = lastrow To 40 Step by - 1

a = a + Worksheets("Invoice").Cells(b, 9).Value

Next

Worksheets("invoice").Cells(lastrow + 2, 9).Value = a

End Sub


How can I create the total where the last cells is not blank

Thanks in advance
 

Excel Facts

How to find 2nd largest value in a column?
MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest
The issue is that your formula sometimes returns a blank, which is a text value, and cannot be used in addition.
You could change your formula to return 0 instead of a blank, i.e.
VBA Code:
=IF(H47<>"",G47*H47,0)
and use Formatting or Conditional Formatting on the column to hide those 0 values, if you do not want to see them.

Or how about just using the SUM function instead?
The big two advantages to using SUM is:
- you do not need to loop, so code will be faster
- SUM automatically ignores Text values, so you do not need to alter your original formula.

To use SUM in VBA, preface it with:
VBA Code:
Application.WorksheetFunction.Sum(...)
 
Upvote 0

Forum statistics

Threads
1,215,139
Messages
6,123,259
Members
449,093
Latest member
Vincent Khandagale

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