2009-10-08 51 views
1

我被要求用一些arcaic編程修改Excel工作表。我決定重寫它,而不是修改所有的GOTO語句和靜態數組。我的背景是在C#中,所以它一直是一個挑戰(注意:我確定命名約定是壞的,我習慣於能夠使用下劃線來定義私有變量)VBA中的字典屬性

我遇到問題了inializing an我在VBA應用程序中的類中的類型字典的屬性。

類的縮短版看起來像這樣

Private pTerminalCode As String 
Private pTerminalName As String 
...... other attributes 
Private pPayRoll As Dictionary 

'Propeties 
Public Property Get terminalCode() As String 
    terminalCode = pTerminalCode 
End Property 
Public Property Let terminalCode(Value As String) 
    pTerminalCode = Value 
End Property 
....... more properties 
Public Property Get headCount() As Dictionary 
    headCount = pHeadCount 
End Property 
Public Property Let headCount(Value As Dictionary) 
    pHeadCount = Value 
End Property 

當我嘗試使用下面我得到的錯誤「參數不可選」的人數()屬性的獲取屬性中。

Private Function PopulateTerminal() 
    Dim terminal As clsTerminal 
    Set terminal = New clsTerminal 

    terminal.terminalCode = "Wil" 
    terminal.headCount.Add "Company", 100 
End Function 

我假設某處我需要inialize字典(即=新詞典),但我正在努力與它放置在哪裏。在C#中,我在構造函數中做這個沒有問題,不知道在這裏做什麼。

感謝

回答

3

你可以做到這一點在VBA類的構造函數,像這樣: -

Public Sub Class_Initialize() 
    Set myDictionary = New Dictionary 
End Sub 

分配的對象引用時,不要忘記常使用Set關鍵字,例如: -

Public Property Get Foo() As Dictionary 
    Set Foo = myDictionary 
End Sub 
+0

集是一個大發現,就是這裏的「參數不可選」錯誤是由正在添加,但是,我現在receieving「對象變量或帶塊變量未設置」 – 2009-10-08 20:01:15

+0

明白了。不知道爲什麼,但如果我在構造函數中初始化,我得到對象變量錯誤,但是如果我在聲明它的工作原理inialize。感謝您的幫助 – 2009-10-08 20:04:14

+0

啊是的,在聲明中初始化是另一種選擇。也許這更好,因爲它會導致延遲初始化。 – 2009-10-08 20:36:12