Excel VBA类中的Dictionary属性

Excel VBA类中的Dictionary属性,excel,vba,dictionary,Excel,Vba,Dictionary,我被要求用一些arcaic编程修改Excel表格。我决定重写它,而不是修改所有的GOTO语句和静态数组。我的背景是C#,因此这有点挑战性(注意:我确信命名约定不好,我习惯于使用下划线来定义私有变量) 在VBA应用程序中的类中初始化类型字典的属性时遇到问题 该类的缩短版本如下所示 Private pTerminalCode As String Private pTerminalName As String ...... other attributes Private pPayRoll As Di

我被要求用一些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#中,我在构造函数中执行此操作,没有问题,不确定在这里执行什么操作


谢谢

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

Public Sub Class_Initialize()
    Set myDictionary = New Dictionary
End Sub
分配对象引用时,不要忘记始终使用
Set
关键字,例如:-

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

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

Public Sub Class_Initialize()
    Set myDictionary = New Dictionary
End Sub
分配对象引用时,不要忘记始终使用
Set
关键字,例如:-

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

集合是一个很好的捕获,这就是“参数非可选”错误产生的原因,然而,我现在收到的“对象变量或块变量未设置”得到了解决。不知道为什么,但是如果我在构造函数中初始化,我会得到对象变量错误,但是如果我在声明中初始化,它会工作。谢谢你的帮助啊是的,在声明中初始化是另一个选项。也许这会更好,因为它会导致延迟初始化。集合是一个很好的捕获,这就是“参数非可选”错误产生的原因,但是,我现在收到“Object Variable或With block Variable not set”解决了它。不知道为什么,但是如果我在构造函数中初始化,我会得到对象变量错误,但是如果我在声明中初始化,它会工作。谢谢你的帮助啊是的,在声明中初始化是另一个选项。也许这会更好,因为它会导致延迟初始化。