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

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
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,148
Messages
6,123,301
Members
449,095
Latest member
Chestertim

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