如何将用户定义的数据类型放入字典 [英] How to put user defined datatype into a Dictionary

查看:241
本文介绍了如何将用户定义的数据类型放入字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to define my own data type and put it in a Dictionary as a value. VBA complains, that it does not accept my data type. Any ideas about how to get this working?

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

这是错误消息:

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

Only user-defined types defined in public object modules can be coerced to or from a variant or passed to late-bound modules.

推荐答案

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

After some more digging i found this answer:

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

If you want to put a user defined data type into a Dictionary of Collection, you have to define it as class. You can do so by adding a new class module and just adding this code:

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

由于我命名了类模块 / em>,我的结果代码如下所示:

Since I named the class module trans, my resulting code looks like this:

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

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

Now I can dynamically add translations.

这篇关于如何将用户定义的数据类型放入字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆