有没有更容易/更好的方法来使用预定义词典?

时间:2019-02-01 18:41:16

标签: excel vba

我有一个对应日期的数字字典。我必须想象有一种比必须存储所有日期然后再调用它们的方法更好的方法。

换句话说,我可以创建一个通用的字典,然后让代码中的其他部分访问该字典,这样我就不会在函数中隐藏全局字典了吗?

 Function Get_Val_Date(Val_Date_Key As Long)
        Dim Date_Dict As Scripting.Dictionary

    Set Date_Dict = New Scripting.Dictionary
    Date_Dict.Add 1, "9/30/1997"
    Date_Dict.Add 2, "9/30/1998"
    Date_Dict.Add 3, "9/30/1999"
    Date_Dict.Add 4, "9/30/2000"
    Date_Dict.Add 10, "9/30/2001"
    Date_Dict.Add 11, "9/30/2002"
    Date_Dict.Add 12, "9/30/2003"
    Date_Dict.Add 13, "9/30/2004"
    Date_Dict.Add 14, "9/30/2005"



    Get_Val_Date = Date_Dict(Val_Date_Key)

 End Function

1 个答案:

答案 0 :(得分:5)

只需在第一次使用时对其进行缓存:

 'Module level
 Private Date_Dict As Scripting.Dictionary

 Function Get_Val_Date(Val_Date_Key As Long)
    If Date_Dict Is Nothing Then
        Set Date_Dict = New Scripting.Dictionary
        Date_Dict.Add 1, "9/30/1997"
        Date_Dict.Add 2, "9/30/1998"
        Date_Dict.Add 3, "9/30/1999"
        Date_Dict.Add 4, "9/30/2000"
        Date_Dict.Add 10, "9/30/2001"
        Date_Dict.Add 11, "9/30/2002"
        Date_Dict.Add 12, "9/30/2003"
        Date_Dict.Add 13, "9/30/2004"
        Date_Dict.Add 14, "9/30/2005"
    End If

    Get_Val_Date = Date_Dict(Val_Date_Key)

 End Function

如果您打算在其他函数中使用相同的字典,则可以将初始化程序拆分为自己的Sub,如下所示:

Function Get_Val_Date(Val_Date_Key As Long)
   InitializeDateLookup
   Get_Val_Date = Date_Dict(Val_Date_Key)
End Function

Sub InitializeDateLookup()
    If Date_Dict Is Nothing Then
        Set Date_Dict = New Scripting.Dictionary
        Date_Dict.Add 1, "9/30/1997"
        Date_Dict.Add 2, "9/30/1998"
        Date_Dict.Add 3, "9/30/1999"
        Date_Dict.Add 4, "9/30/2000"
        Date_Dict.Add 10, "9/30/2001"
        Date_Dict.Add 11, "9/30/2002"
        Date_Dict.Add 12, "9/30/2003"
        Date_Dict.Add 13, "9/30/2004"
        Date_Dict.Add 14, "9/30/2005"
    End If
End Sub

那么任何需要它的过程都可以调用单行InitializeDateLookup