vba 如何将用户定义的数据类型放入字典中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9178177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to put user defined datatype into a Dictionary
提问by BetaRide
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?
我正在尝试定义我自己的数据类型并将其作为值放入字典中。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
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.
只有在公共对象模块中定义的用户定义类型才能被强制传入或传出变体或传递给后期绑定模块。
回答by BetaRide
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:
由于我将类模块命名为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
Now I can dynamically add translations.
现在我可以动态添加翻译。