Dynamic Sum Reference

MikeG

Well-known Member
Joined
Jul 4, 2004
Messages
845
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
I have a macro that includes the following:


============================================
a = Selection.Row
b = Selection.Rows.Count
Cells(a + b, 1).Select

Selection.EntireRow.Insert

column_to_sum = 4

ActiveCell.Formula = "=sum(D1:D3)"

=============================================

What I want to do is make the ActiveCell.Formula line dynamic, so instead of hard-coding D1:D3, I want the column to be based on the value of the column_to_sum variable (currently 4, but could be other) and the rows to be summed to be from the value of variable a to variable a + b -1.

In effect something like =sum(range(Cells(a, column_to_sum), cell(a+b-1, column_to_sum)))

...if you see what I mean.

Thanks,

Mike
 

Excel Facts

Why are there 1,048,576 rows in Excel?
The Excel team increased the size of the grid in 2007. There are 2^20 rows and 2^14 columns for a total of 17 billion cells.
Try:
Code:
Dim RngToSum as Range
set RngToSum= range(Cells(a, column_to_sum), cells(a+b-1, column_to_sum))
ActiveCell.Formula = "=sum(" & RngToSum.Address & ")"
 
Upvote 0
Try:
Code:
Dim RngToSum as Range
set RngToSum= range(Cells(a, column_to_sum), cells(a+b-1, column_to_sum))
ActiveCell.Formula = "=sum(" & RngToSum.Address & ")"

Thanks JoMo - that's just what I need.

MikeG
 
Upvote 0

Forum statistics

Threads
1,224,594
Messages
6,179,794
Members
452,943
Latest member
Newbie4296

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