ACC2: Sample Function Using Recursion to Display Data TreeID: Q132242
|
This article demonstrates how you can create a sample user-defined Access
Basic function that calls itself multiple times in order to loop through a
linked list of items. You can use this technique to display data in a tree
structure such as a directory of managers and employees.
This article assumes that you are familiar with Access Basic and with
creating Microsoft Access applications using the programming tools provided
with Microsoft Access. For more information about Access Basic, please
refer to the "Building Applications" manual.
To create a sample user-defined Access Basic function that calls itself
multiple times, follow these steps:
Option Explicit
Function Start_List (EmpID As Long)
Dim db As Database, rs As Recordset
Set db = CurrentDB()
Set rs = db.OpenRecordset("Employees2", DB_OPEN_TABLE)
rs.Index = "Primarykey"
rs.Seek "=", EmpID
If rs.NoMatch Then Exit Function
Debug.Print EmpID & " " & rs![first name] & " "; rs![last name]
rs.Index = "MgrID"
List_Employees rs, EmpID, 1
rs.Close
db.Close
End Function
NOTE: In the following sample code, an underscore (_) at the end of a
line is used as a line-continuation character. Remove the underscore
from the end of the line when re-creating this code.
Sub List_Employees (rs As Recordset, ByVal MgrID As Long, ByVal _
level As Integer)
Dim bm As String
rs.Seek "=", MgrID
If rs.NoMatch Then Exit Sub
Do While Not rs.EOF
If rs!MgrID <> MgrID Then Exit Sub
Debug.Print String$(level,9) & rs!EmpID & " " & rs! _
[first name]& " "; rs![last name]
bm = rs.BookMark ' Save place in the recordset.
List_Employees rs, rs!EmpID, level + 1
rs.BookMark = bm ' Return to proper place for this level.
rs.MoveNext
Loop
End Sub
2 Andrew Fuller
1 Nancy Davolio
3 Janet Leverling
11 Tim Smith
12 Caroline Patterson
4 Margaret Peacock
5 Steven Buchanan
6 Michael Suyama
7 Robert King
9 Anne Dodsworth
8 Laura Callahan
10 Albert Hellstern
13 Justin Brid
14 Xavier Martin
Microsoft Access "Building Applications," version 2.0, Chapter 11, "Working With Sets of Records," pages 242-267
Additional query words: recursive re-enterable re-entry bill of material
Keywords : kbprg PgmPrcs
Version : 2.0
Platform : WINDOWS
Issue type : kbinfo
Last Reviewed: April 22, 1999