自定义 Excel 函数中的 VBA 字典

问题描述 投票:0回答:2

我想制作一个自定义函数来替换/翻译单词(大约 4000 个单词)。我设法在函数内创建并填充字典,但这似乎非常多余,每次调用函数时都会创建字典。所以我想在函数外部创建字典并在函数内部使用它,如下所示:

Option Explicit

Sub make_dict()

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
         
    With dict
    
        .Add "house", "Haus"
        .Add "dog", "Hund"
        .Add "cat", "Katze"
    
    End With

End Sub

Function translate(ByRef a_word As String) As String
    
    '~~> how to reference dictionary here ?
  
    If Len(a_word) = 0 Then
        translate = "#NA"
        Exit Function
    End If
    
    Dim found As Boolean
    found = False
    For Each k In dict.keys
        key = k
        If key = a_word Then
            translate = dRL.Item(k)
            found = True
            Exit Function
        End If
    Next k
    
    If found = False Then
        translate = "#NA"
    End If
    
End Function

但是,当将函数调用为

时,我找不到引用字典的正确方法

=translate(A1)

单元格 A1 中包含字符串“dog”

excel vba function dictionary
2个回答
0
投票

您可以使用静态变量:

Option Explicit

Sub make_dict(dict As Object)
    Debug.Print "called"
    Set dict = CreateObject("Scripting.Dictionary")
         
    With dict
    
        .Add "house", "Haus"
        .Add "dog", "Hund"
        .Add "cat", "Katze"
    
    End With

End Sub

Function translate(ByRef a_word As String) As String
    Static dict As Object
    If dict Is Nothing Then make_dict dict
    '~~> how to reference dictionary here ?
  
    If Len(a_word) = 0 Then
        translate = "#NA"
        Exit Function
    End If
    
    Dim found As Boolean
    found = False
    Dim k
    For Each k In dict.keys
        If k = a_word Then
            translate = dict.Item(k)
            found = True
            Exit Function
        End If
    Next k
    
    If found = False Then
        translate = "#NA"
    End If
    
End Function

0
投票

您的字典需要是一个全局变量,您可以使用如下所示的方法来返回或创建并返回字典(如果字典不存在)。

Dim GlobalDict as Object

Function GetDict() as Object
    If GlobalDict is Nothing then
        'populate global dictionary
    End If
    Set GetDict = GlobalDict
End Function
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.