Creating recursive procedures
Procedures have a limited amount of space for variables. Each time a procedure calls itself, more of that space is used. A procedure that calls itself is a recursive procedure. A recursive procedure that continuously calls itself eventually causes an error. For example:
Function RunOut(Maximum)
RunOut = RunOut(Maximum)
End Function
This error may be less obvious when two procedures call each other indefinitely, or when some condition that limits the recursion is never met. Recursion does have its uses. For example, the following procedure uses a recursive function to calculate factorials.
Function Factorial (N)
If N <= 1 Then ' Reached end of recursive calls.
Factorial = 1 ' (N = 0) so climb back out of calls.
Else ' Call Factorial again if N > 0.
Factorial = Factorial(N - 1) * N
End If
End Function
You should test your recursive procedure to make sure it does not call itself so many times that you run out of memory. If you get an error, make sure your procedure is not calling itself indefinitely. After that, try to conserve memory by:
- Eliminating unnecessary variables.
- Using data types other than Variant.
- Re-evaluating the logic of the procedure. You can often substitute nested loops for recursion.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기