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

  • 本文关键字:VB 数组 创建 模块 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,所以我可能被一些明显的东西绊倒了......

解决方法

是在初始化它们时将它们声明为 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

最新更新