2016-01-18 82 views
2

我想在使用面向對象概念的excel VBA中編寫一些代碼。因此我想用構造函數初始化我的對象,就像我們通常在Java中所做的那樣。但是,我發現在VBA中提供的默認Class_Initialize() Sub不帶參數。經過一番搜索,我發現這個Question的答案提出了一個很好的選擇。VBA中的構造函數 - 運行時錯誤91「對象變量未設置」

這裏是我廠模塊的樣品(我把它命名造物主):

Public Function CreateTool(ToolID As Integer) As cTool 
    Set CreateTool = New cTool 
    CreateTool.InitiateProperties (ToolID)  '<= runtime error 91 here 
End Function 

cTool

Private pToolID As Integer 
Private pAttributes As ADODB.Recordset 
Private pCnn As ADODB.Connection 

Public Sub InitiateProperties(ToolID As Integer) 
    Dim sSQL As String 
    Set pCnn = connectToDB()  'A function that returns a connection to the main DB 
    pToolID = ToolID 
    sSQL = "SELECT Tool_ID, Status, Type, Tool_Number " _ 
       & "FROM Tool WHERE Tool_ID = " & pToolID 
    pAttributes.Open sSQL, pCnn, adOpenKeyset, adLockOptimistic, adCmdText 
End Sub 

這是我如何調用構造函數:

Dim tool As cTool 
Set tool = Creator.CreateTool(id) 

我的問題是,當我運行的代碼,我收到以下錯誤:

運行時錯誤「91」:對象變量或帶塊變量未設置

調試凸顯CreateTool.InitiateProperties (ToolID)我的線CreateTool函數。

我知道這種情況通常發生在有人在不使用關鍵字Set的情況下爲某個對象設置一個值時,但這似乎並不是我的情況。

任何幫助,建議來解決這個問題將不勝感激!

謝謝。

+2

您尚未在cTool.InitateProperties中創建pAttributes對象。 – Jules

+0

謝謝!我從來沒有想過檢查我的* cTool *類,因爲調試器指向別的地方。添加行'Set pAttributes = New ADODB.Recordset'解決了這個問題。再次感謝您的快速回復。我將編輯我的文章,包括你回答 –

+0

不要這樣做。這是一個問答網站,而不是論壇。問題應該包含問題,答案應該包含答案。 –

回答

3

可能不是你錯誤的原因,但這樣:

Public Function CreateTool(ToolID As Integer) As cTool 
    Set CreateTool = New cTool 
    CreateTool.InitiateProperties (ToolID)  '<= runtime error 91 here 
End Function 

是對一些原因問題。試想一下:

Public Function CreateTool(ByVal ToolID As Integer) As cTool 
    Dim result As cTool 
    Set result = New cTool 
    result.InitiateProperties ToolID 
    Set CreateTool = result 
End Function 

現在,看着你的代碼的其餘部分,你做的VBA相當於在構造做的工作,即數據庫訪問等副作用來構建你的對象。

作爲@Jules correctly identified,您正在訪問InitiateProperties內部的單位化對象pAttributes - 這很可能是您的問題的原因。

我倒是強烈推薦另一種方法 - 如果你來自Java中,你知道做一個構造函數裏面的工作是不好的設計......同樣適用於VBA。

讓您的代碼正常工作,並將其全部發布到Code Review Stack Exchange以獲得完整的同行評審。

+0

謝謝,我會相應地修改我的代碼。我不知道Code Review Stack Exchange。我會更頻繁地使用它! –

+2

@OscarAnthony請記住,Code Review是一個**工作**代碼被審查的地方,而不是一個地方要求_如何使它工作_,而是_如何使它工作_ **更好**。 –

相關問題