VBA类中的字典属性

时间:2009-10-08 19:41:43

标签: excel vba dictionary

我被要求用一些arcaic编程来修改Excel表格。我决定重写它而不是修改所有的GOTO语句和静态数组。我的背景是在C#中,所以它有点挑战(注意:我确定命名约定很糟糕,我习惯使用下划线来定义私有变量)

我无法在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

当我尝试使用以下内容时,我在headCount()属性的Get属性中收到错误“Argument not optional”。

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

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

我假设某个地方需要将词典(即=新词典)归化,但是我对它的位置感到不安。在C#中,我在构造函数中执行此操作时没有问题,不知道该怎么做。

由于

1 个答案:

答案 0 :(得分:4)

您可以在VBA类的构造函数中执行此操作,如下所示: -

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

在分配对象引用时,不要忘记始终使用Set关键字,例如: -

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