VBA中的递归函数调用

时间:2015-02-02 00:34:26

标签: excel vba

我试图在VBA(excel)中编写递归函数调用,该函数创建组织结构中所有员工的脚本字典(直接和间接)。

函数 Get_Underling_Staff_IDs 具有double类型的staff_ID的输入参数,即数据库ID /员工编号。该函数应返回一个脚本字典,其中每个元素都是员工编号(双精度)。

我无法让函数在递归庄园中运行,允许它在调用例程的一次调用中从组织结构中的任何位置导航到底部。

到目前为止,我有以下内容:

Function Get_Underling_Staff_IDs(MANAGER_ID As Double) As Scripting.Dictionary

' an instance of a single staff id that DIRECTLY reports to the MANAGER
Dim Direct_Underling_Staff              As Variant
' A dictionary of all the staff id's that DIRECTLY report to the MANAGER
Dim All_Direct_Underling_Staff          As Scripting.Dictionary

' an instance of a single staff id that INDIRECTLY reports to the MANAGER
Dim Indirect_Underling_Staff            As Variant
' A dictionary of all the staff id's that INDIRECTLY report to the MANAGER
Dim All_Indirect_Underling_Staff        As Scripting.Dictionary


Set Get_Underling_Staff_IDs = New Scripting.Dictionary

' Get a dictionary of all the employees that directly report to the MANAGER_ID
Set All_Direct_Underling_Staff = Get_Relation_Staff_Manager(MANAGER_ID)

For Each Direct_Underling_Staff In All_Direct_Underling_Staff

    If Not Get_Underling_Staff_IDs.Exists(Direct_Underling_Staff) Then
        Get_Underling_Staff_IDs.Add Direct_Underling_Staff, Direct_Underling_Staff
    End If

Next Direct_Underling_Staff

For Each Direct_Underling_Staff In Get_Underling_Staff_IDs

    ' Get All the Employees that indirectly report to the MANAGER_ID
    Set All_Indirect_Underling_Staff = Get_Relation_Staff_Manager(CDbl(Direct_Underling_Staff))

    If Not Get_Underling_Staff_IDs.Exists(Indirect_Underling_Staff) Then
        Get_Underling_Staff_IDs.Add Indirect_Underling_Staff, Indirect_Underling_Staff
    End If

Next Direct_Underling_Staff


End Function

我在哪里错了?

员工ID长度为5位数:例如55707

"经理"是间接员工老板的老板。 (老板'老板)

感谢您的帮助。

亲切的问候 约旦

1 个答案:

答案 0 :(得分:0)

未测试:

Function Get_Team_Staff_IDs(MANAGER_ID As Double, _
         Optional dictAll As Scripting.dictionary) As Scripting.dictionary

    Dim dictDirect As Scripting.dictionary, k

    If dictAll Is Nothing Then
        'First call does not have a dictionary argument,
        '  so create a new one to hold the id's
        Set dictAll = New Scripting.dictionary
    End If

    Set dictDirect = Get_Direct_Reports(MANAGER_ID)
    For Each k In dictDirect
        'add this report
        If Not dictAll.Exists(k) Then dictAll.Add k, k
        'see if this report has their own reports
        Get_Team_Staff_IDs CDbl(k), dictAll
    Next k

    'Return the final set of id's to the
    '  original caller (was called as a function)
    Set Get_Team_Staff_IDs = dictAll

End Function