PDA

View Full Version : How to return the sum of variables which change in a loop



haarish4life
02-23-2006, 07:26 AM
Hi there !
Just wanted to ask you a quick question. I've a VBA code which changes accordingt an input parameter i which changes every time depending where it is in the loop.
say for example the return value is return(j) which changes for each value of j.

I want a code which will return the value of the sum of all the return(j) for j=1 to n
I have tried using

Sub g()
for j =1 to n
Return (j) = .......someinputformla which is dependent on (j)
g=worksheetfunction.sum(return(j))
Cells(1,1) = g
Next j
End sub

But it does not work....basically,i just wanna know how to sum the return (j)
Thanks for yourtime
Regards
Haarish

Norie
02-23-2006, 08:28 AM
Haarish

It isn't clear, to me anyway, what you actually want to sum.

lucas
02-23-2006, 09:25 AM
Hi Haarish,
Since this appears to be an excel question(reference to worksheet) I am going to move this thread to the Excel help forum so that others looking to help with excel questions can find it.....

mdmackillop
02-24-2006, 12:39 PM
Hi Haarish,
Welcome to VBAX

Try something like



Sub AddJ()
Dim g As Double, j As Long
g = 0
For j = 1 To [A1]
g = g + DoStuff(j)
Next j
Cells(2, 1) = g
End Sub


Function DoStuff(j As Long) as Double
Select Case j
Case Is < 3
DoStuff = j ^ 3
Case Is < 10
DoStuff = j ^ 4
Case Is < 20
DoStuff = j ^ 2
End Select
End Function

XLGibbs
02-24-2006, 05:11 PM
MD,

I like the function name! I use the stuff suffix frequently...especially with my ToggleStuff routine I usually use to handle events and screenupdating.

Hopefully the OP comes back with more questions or to advise if the suggestion worked or could be applied to his need...