在类模块中创建公共的VB数组

时间:2013-11-09 20:28:56

标签: excel vba

快速摘要 - 我正在使用一些遗留代码,我需要添加一个带有字符串数组的类,并因无法声明一个公共字符串数组而跳闸。

更多:

我有一个带有Excel工作表的VB代码,该工作表在不同的人身上有200行数据。每个人的数据将由代码重新混合,并分流到Word模板中以生成个人报告。我需要添加另一段代码,如下所示:

我创建了一个类类型MotivationBuckP,我想创建该类的四个对象,其中包含可变长度的字符串数组。 (如果这更容易,我可以用固定长度对它进行编码)

数组开始为空,将根据特定个人的数据填充。我正在使用数组,因为虽然有一定数量的字符串内容(18个标题和18个较长的文本位),但是每个人都会在四个对象中分配不同的数据(想想每个人都是18加仑的桶注入四桶)

我理解在类模块中我需要将所有变量声明为Public,例如:

Public MotivID As Integer
Public MotivQuant As Integer
Public strMotivatorTitle() As String
Public strMotivatorDescriptor() As String

但是为了回应最后2个变量的存在,运行给了我错误:

Compile error: 
Constants, fixed-level strings, arrays, user-defined types and Declare statements are not allowed as Public members of object modules

由于现有代码的限制,我需要在多个模块中创建和使用strMotivatorTitle和strMotivatorDescriptor变量。但我明白我不能这样做,除非它是公开声明的(并且,我认为,在类模块中)。所以这就是我撞墙的地方。

任何帮助非常感谢。自从我的博士学位以来,我没有大量使用过VB,所以我可能被明显的东西绊倒了......

1 个答案:

答案 0 :(得分:4)

解决方法是在初始化时将它们声明为VariantReDim作为字符串数组

Public strMotivatorTitle As Variant 
Public strMotivatorDescriptor As Variant

初始化为数组,例如

Private Sub Class_Initialize()
    ReDim strMotivatorTitle(0 To 9)

    strMotivatorTitle(0) = "Foo"
    strMotivatorTitle(1) = "Bar"
    ' etc
End Sub

另一种方法是,将字符串数组声明为Private并使用`Property Get'访问它们

Private pMotivatorTitle() As String
Private pMotivatorDescriptor() As String

Property Get strMotivatorTitle() As String()
    strMotivatorTitle = pMotivatorTitle
End Property

Property Get strMotivatorDescriptor() As String()
    strMotivatorDescriptor= pMotivatorDescriptor 
End Property