从 VBA 中的函数返回对象实例时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2210239/
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
Error returning object instance from function in VBA
提问by ChrisDiRulli
I'm trying to instantiate an object and return it from a function. The class I'm working with is one that I've created. However when I try to set an Object to what was returned from the function I get an error. What am I doing wrong?
我正在尝试实例化一个对象并从函数中返回它。我正在使用的课程是我创建的课程。但是,当我尝试将 Object 设置为从函数返回的内容时,出现错误。我究竟做错了什么?
Function CreateBlah(NAME As String, Count As Integer, val As String) As Blah
Dim b As Blah
Set b = New Blah
bkmrk.Initialize NAME, Count, val
MsgBox (bkmrk.NAME)
CreateBlah = bkmrk
End Function
Then in the other function...
然后在另一个函数中......
Dim bmrk As Blah
Set bmrk = CreateBlah("Test", 1, Trim(AString))
I also tried...
我也试过...
Dim bmrk As Object
Set bmrk = CreateBlah("Test", 1, Trim(AString))
I'm new to VBA, can anyone tell me what I'm doing wrong?
我是 VBA 新手,谁能告诉我我做错了什么?
回答by Oorang
You need to use set everytime you assign an object. This means when setting return value and when assigning the return value to a variable. Late Bound Example:
每次分配对象时都需要使用 set 。这意味着在设置返回值和将返回值分配给变量时。后期绑定示例:
Public Sub Example()
Dim objWrd As Object
Set objWrd = GetWord
objWrd.Visible = True
objWrd.Quit
End Sub
Public Function GetWord() As Object
Set GetWord = CreateObject("Word.Application")
End Function
Early Bound Example:
早期绑定示例:
Public Sub Example()
''//Requires reference to Microsoft Office Word
''//(Tools>References)
Dim objWrd As Word.Application
Set objWrd = GetWord
objWrd.Visible = True
objWrd.Quit
End Sub
Public Function GetWord() As Word.Application
Set GetWord = New Word.Application
End Function
回答by Adam Ralph
I assume that
我假设
Dim b As Blah
Set b = New Blah
should actually read
实际上应该阅读
Dim bkmrk As Blah
Set bkmrk = New Blah
if so, you're missing a set keyword.
如果是这样,则您缺少 set 关键字。
Set CreateBlah = bkmrk
Once you've fixed this then both versions of your consuming code should work, although the former is better since you are strongly typing the variable.
一旦你解决了这个问题,那么你的消费代码的两个版本都应该可以工作,尽管前者更好,因为你强烈地输入了变量。

