vba 如何在vba函数中传递类变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9737749/
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 pass class variables in vba function
提问by Rijk
I want to pass my set of objects and variables to VBA function, make some changes to it and pass it back as a result. So I create a sample Class1:
我想将我的一组对象和变量传递给 VBA 函数,对其进行一些更改并将其作为结果传回。所以我创建了一个示例 Class1:
Public pInfo As String
and sample function:
和示例功能:
Public Function populate(someVar As Class1) As Class1
populate.pInfo = someVar.pInfo & " 1 "
End Function
and tryed to pass it to my function populate:
并尝试将其传递给我的函数填充:
Sub test()
Dim v, w As Class1
Set v = New Class1
v.pInfo = "303"
Set w = populate(v) ' ERROR here
End Sub
results in compile error : byRef argument type mismatch.
导致编译错误:byRef 参数类型不匹配。
UPDATE. Thanks to your help it compiles now.
更新。感谢您的帮助,它现在可以编译了。
回答by Alex K.
Its a type error
这是一个类型错误
Dim v, w As Class1
Unintuitively here only w
is of type Class1
, v
is a variant.
To make them both Class1
you must:
不直观的这里只是w
type Class1
,v
是一个变体。要使它们同时存在,Class1
您必须:
Dim v As Class1, w As Class1
Here:
这里:
Public Function populate(someVar As Class1) As Class1
populate.pInfo = someVar.pInfo & " 1 "
End Function
populate
is not an instance of Class1
, you need to create it:
populate
不是 的实例Class1
,您需要创建它:
Public Function populate(someVar As Class1) As Class1
set populate = new Class1
populate.pInfo = someVar.pInfo & " 1 "
End Function
(Rather than using a function you may prefer a v.copyTo(w)
)
(而不是使用您可能更喜欢的函数v.copyTo(w)
)
回答by markblandford
You also need to correct your Populate()
method as follows:
您还需要Populate()
按如下方式更正您的方法:
Public Function Populate(someVar As Class1) As Class1
Dim z as Class1
Set z = New Class1
z.pInfo = someVar.pInfo & " 1 "
Set Populate = z
Set z = Nothing
End Function
You also need to be aware that this will create a new instance of Class1
so it will not inherit any of the other properties from someVar
.
您还需要注意,这将创建一个新实例,Class1
因此它不会从someVar
.