Written by Rod Wing.
Using Recursion in VBA
Recursion is a programming technique where a sub or function calls itself. There are many examples where this can come in very useful and eliminate a lot of copying and pasting of code. A common task in MicroStation where this can be put to use is iterating through groups of elements containing both simple and complex elements using an ElementEnumerator.
The following ProcessText function illustrates how recursion can be used to filter out and modify text elements from a set of elements. Text Node and Cell elements are two types of complex elements that can contain simple text elements that we want to process. Using the GetSubElements method of a complex element type we can obtain a new ElementEnumerator and call the ProcessText function again to look for text elements inside the complex element.
Public Function ProcessText(ee As ElementEnumerator) As Boolean
Dim i As Long Dim iStart As Long Dim iEnd As Long Dim elArray() As Element
On Error GoTo ERROR_HANDLER
ProcessText = False
If ee Is Nothing Then
Exit Function
End If
elArray = ee.BuildArrayFromContents iStart = LBound(elArray) iEnd = UBound(elArray)
For i = iStart To iEnd
Select Case elArray(i).Type
Case MsdElementType.msdElementTypeText
With elArray(i).AsTextElement
' ' Modify text element here '
End With
elArray(i).Rewrite
Case MsdElementType.msdElementTypeTextNode
' GetSubElement returns an ElementEnumerator containing text elements within text node ' use recursive function call to process new enumerator If Not ProcessText(elArray(i).AsTextNodeElement.GetSubElements) Then
Exit Function
End If
Case MsdElementType.msdElementTypeCellHeader
' GetSubElement returns an ElementEnumerator containing elements within cell ' use recursive function call to process new enumerator to process any text elements in cell If Not ProcessText(elArray(i).AsCellElement.GetSubElements) Then
Exit Function
End If
End Select
Next
ProcessText = True
Exit Function
ERROR_HANDLER:
MsgBox "ProcessText Error: " & CStr(Err.Number) & Err.Description
End Function