556 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owls only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
Writing recursive programs in VBA Part four of a four-part series of blogs |
---|
In certain cases in VBA (displaying the contents of folders, listing hierarchical data) writing a program which calls itself is by far the easiest way to go - this blog gives worked examples of 3 such recursive programs.
This blog is part of our Excel VBA tutorial series of blogs (consider also booking on one of our Visual Basic for Applications courses).
|
The factorial of a number is written (in the UK at any rate) as n!. For example:
Notice that for any n:
To the experienced programmer, this is crying out for a program which will call itself recursively.
The program below will show one of two things:
![]() |
![]() |
Output if the factorial isn't too big | Output if the number is too large |
Here is the suggested program. First we set some global variables (including the seed whose factorial we'll calculate):
Option Explicit
'allow fairly large numbers
Dim CurrentFactorial As Long
'detect if this wasn't enough
Dim IfOverflow As Boolean
'number whose factorial we'll calculate
Const Seed As Integer = 10
Next, we'll write our subroutine which calls itself recursively:
Sub GetFactorial(n As Integer)
'if we've had an overflow, no point continuing
If IfOverflow Then Exit Sub
'if an error happens, set flag and exit
On Error GoTo Overflow
'if we've got down to 1, exit
If n <= 1="">=>Then Exit Sub
'multiply by this number and recursively get the next factorial down
CurrentFactorial = CurrentFactorial * n
GetFactorial (n - 1)
'finished - exit
Exit Sub
Overflow:
IfOverflow = True
End Sub
The important line is the one I've put in bold: the GetFactorial subroutine calls itself, with a number one less each time.
Finally, we need to write a program to call the GetFactorial subroutine in the first place, and to display its result:
Sub ShowFactorials()
'initially there is no overflow problem ...
IfOverflow = False
'... and factorial equals 1
CurrentFactorial = 1
'call routine to find factorial
Call GetFactorial(Seed)
'if a problem say so - otherwise, return answer
If IfOverflow Then
MsgBox "Too large a number generated - try something smaller"
Else
MsgBox "Factorial of " & Seed & " is " & CurrentFactorial
End If
End Sub
When you run this last subroutine, you'll see the factorial of the number you chose as a seed!
Parts of this blog |
---|
|
Some other pages relevant to the above blogs include:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2023. All Rights Reserved.