Sum in a function with a variable

stephicohu

New Member
Joined
Jan 27, 2023
Messages
26
Office Version
  1. 365
Platform
  1. MacOS
I am new in excel vba and have a question that you have answered previously. I cannot find the answer in your database because I can't remember how I word the question. I have the following code:

Dim Num1 As Integer

Num1 = -10

Range("AO3").Select
ActiveCell.FormulaR1C1 = "=SUM(RC[" & Cstr(Num1)"]:RC[-9], February!RC[-39]:RC[-35])"

What I am trying to do is to place the Num1 into the sum function so I can change the value of Num1. How do I do this without having an error on the value. I have tried many ideas and they have failed. Help!
 

Excel Facts

Can you sort left to right?
To sort left-to-right, use the Sort dialog box. Click Options. Choose "Sort left to right"
I think it's because you're missing an ampersand ( & ) in the concatenation

"=SUM(RC[" & Cstr(Num1) & "]:RC[-9], February!RC[-39]:RC[-35])"
 
Upvote 0
Please mark your thread as solved so that others don't spend time when they're looking for issues to solve.
Thanks.
 
Upvote 0
Welcome to the MrExcel board!

A few additional observations.
  • Excel converts all Integer variables to Long values before using them so you might as well declare them as Long to start with (besides, it is shorter to type anyway ;))
  • There is generally no need to actually select cells/ranges before working with them and selecting slows your code. there is no need to select in this case - see my code below.
  • There is no need to to coerce the numerical Num1 value to string to put it in the formula - vba will automatically handle that for you.
So, the code could look like this
VBA Code:
Dim Num1 As Long

Num1 = -10

Range("AO3").FormulaR1C1 = "=SUM(RC[" & Num1 & "]:RC[-9], February!RC[-39]:RC[-35])"
 
Upvote 0

Forum statistics

Threads
1,214,918
Messages
6,122,241
Members
449,075
Latest member
staticfluids

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