Why doesn't a recursive program work?

DavidSCowan

Board Regular
Joined
Jun 7, 2009
Messages
78
Hi

I am trying to learn about recursive programs but when I write a really simple one - to sum numbers up to n - I get #VALUE! error. Can someone please tell me what i am doing wrong.
Function mySum(n)
Dim n As Integer
Dim result As Integer
If n <= 1 Then
result = 1

Else: result = n + mySum(n - 1)
End If
mySum(n) = result
End Function

Thank you
 
Did you remove your old version and did you force the function to recalculate by re-entering it after altering the code?
 
Upvote 0

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
Hi Inzuri

Thank you very much for engaging with this. I have the function saved in a module in a file which contains all my subs. I am testing it in a worksheet in this same workbook by typing "=my" which brings up all the "mys" including "mySumRoryA" which is Rory's version and I then insert the number so in the cell "mySumRoryA(4)". When I put -4, as Andrew did, I get the correct answer i.e. 1. But any other number e.g. 4 returns the error!

I just can't see why it doesn't work!

David
 
Upvote 0
Rory

Thank you very much for your reply.

No I didn't remove the old version although I took out the dim statement but I put your's in with a different name "mySumRoryA" which I am now using. And yes I did make tt he formula recalculate by always reentering the formula from scratch.

David
 
Upvote 0
Please copy and paste here the exact code you now have for my version.
 
Upvote 0
Hi Rory

In preparing to copy and paste the exact code I have been using I have found an error which i made when I renamed the function containing your code - many apologies! All's well now.

Thank you very much for all your attention in this matter.
 
Upvote 0

Forum statistics

Threads
1,223,244
Messages
6,170,976
Members
452,372
Latest member
Natalie18

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