返回对象的函数抛出错误

时间:2015-09-09 10:38:10

标签: vba object access-vba return-type

我有一个应该返回类对象的函数。该函数如下所示:

Public Function GetPerson(personID As Integer) As clsPerson
    Dim sqlAdapter As New clsSQLAdapter
    Dim person As New clsPerson
    Dim recordset As recordset

    query = "SELECT ID, Anrede_ID, Nachname, Vorname FROM Person WHERE Person.ID = " & personID

    Set recordset = sqlAdapter.recordset(query)
    person.personID = recordset.Fields(0).Value
    If (recordset.Fields(1).Value = kAnrede.FRAU) Then
        Set person.anrede = kAnrede.FRAU
    ElseIf (recordset.Fields(1).Value = kAnrede.HERR) Then
        Set person.anrede = kAnrede.HERR
    End If
    person.nachName = recordset.Fields(2).Value
    person.vorName = recordset.Fields(3).Value
    Set GetPerson = person
End Function

但是当我从另一个模块调用该函数时,我在行

处收到错误91
person = sqlController.GetPerson(1)

说明:"对象变量或未设置块变量":

Private Sub Button_Click()
    Dim sqlController As New clsSQLController
    Dim person As New clsPerson

    person = sqlController.GetPerson(1)

End Sub

当我调试程序时,它告诉我 sqlController.GetPerson(1)的类型是Integer。 甚至可以这样做,还是我错过了什么?

1 个答案:

答案 0 :(得分:0)

好的,所以我自己得到了答案。如果你知道的话,这并不难,我想。

使用Public Function GetPerson(personID As Integer) As clsPerson,您似乎只将函数类型声明为clsPerson,但该函数没有clsPerson的实例。 所以你需要在函数内部创建一个实例,如下所示:

Public Function GetPerson(personID As Integer) As clsPerson

    Set GetPerson = New clsPerson '<- This line is the important part

    'All the other code

    Set GetPerson = person
End Function