如何将用户定义的数据类型放入Dictionary中

时间:2012-02-07 14:39:26

标签: excel vba excel-2010

我正在尝试定义自己的数据类型并将其作为值放入Dictionary中。 VBA抱怨它不接受我的数据类型。关于如何使这个工作的任何想法?

Option Explicit

Public Type Translation
    german As String
    french As String
    italian As String
End Type

Private resource As Object

Public Sub addTranslation(key As String, g As String, f As String, i As String)
    Dim trx As Translation
    trx.german = g
    trx.french = f
    trx.italian = i

    resource.add key, trx  '<== here VBA is complaining
End Sub

Public Sub initResource()
    If resource Is Nothing Then Set resource = CreateObject("scripting.dictionary")
End Sub

这是错误消息:

  

只有在公共对象模块中定义的用户定义类型才能被强制转换为变体或从变体强制传递或传递给后期绑定模块。

1 个答案:

答案 0 :(得分:12)

经过一番挖掘,我发现了这个答案:

如果要将用户定义的数据类型放入Collection of Dictionary,则必须将其定义为类。您可以通过添加新的类模块并添加此代码来实现:

Public german As String
Public french As String
Public italian As String

由于我将类模块命名为 trans ,因此生成的代码如下所示:

Private resource As Object

Public Sub addTranslation(k As String, g As String, f As String, i As String)
    Dim trx As trans
    Set trx = New trans
    trx.german = g
    trx.french = f
    trx.italian = i

    resource.Add k, trx
End Sub

Public Sub initTranslations()
    If resource Is Nothing Then Set resource = CreateObject("scripting.dictionary")
End Sub

现在我可以动态添加翻译。