How to put user defined datatype into a Dictionary

我的梦境 提交于 2019-11-29 12:18:12

问题


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

This is the error messge:

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


回答1:


After some more digging i found this answer:

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

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.



来源:https://stackoverflow.com/questions/9178177/how-to-put-user-defined-datatype-into-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!