2015-09-09 29 views
0

我有一個函數應該返回一個類的對象。功能如下:返回對象的函數拋出錯誤

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 

但是,當我調用該函數從另一個模塊,我在該行

person = sqlController.GetPerson(1) 

,說明得到一個錯誤91:「對象未設置變量或與塊變量「:

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

    person = sqlController.GetPerson(1) 

End Sub 

此外,當我調試PROGRAMM,它告訴我,sqlController.GetPerson的種類(1)是整數。 甚至有可能做到這一點,或者我錯過了什麼?

回答

0

好了,所以我自己得到了答案。我想,如果你知道它並不難。

With 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 
0

我想你只需要一個Set語句添加到您的事件處理程序:

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

    Set person = sqlController.GetPerson(1) 

End Sub 
+0

完全相同的錯誤(91)如果我嘗試這個。 – Nils

0

使用

「返回的人」而不是「設置GetPerson =人

+0

這是VBA,而不是VB.net。我自己找到答案,看到這[回答](http://stackoverflow.com/questions/32477296/function-returning-an-object-throws-error/32479271#32479271)。 – Nils