开发者

Error returning object instance from function in VBA

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?

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?


You need to use set every time you assign an object. This means when setting return value and when assigning the return value to a variable. Late Bound Example:

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


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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜