快速摘要-我正在处理一些旧代码,在这些代码中,我需要添加带有字符串数组的类,并且由于无法声明公共字符串数组而陷入困境。
更多:
我有一个VB代码和一个Excel工作表,该工作表中有200行关于不同个人的数据。每个人的数据将通过代码进行重新混合,然后分流到Word模板中以生成有关该人的报告。我需要添加另一段代码,如下所示:
我创建了一个MotivationBuckP类类型,我想创建该类的四个对象,这些对象包含可变长度的字符串数组。(如果这样更容易,我可能会用固定长度的代码进行编码)
数组开始为空,并将根据特定个人的数据进行填充。我使用数组是因为尽管有固定数量的字符串内容(18个标题和18个较长的文本位),但每个人在四个对象上的分配方式都不同(想像每个人将18加仑的桶倒入四桶)
我了解在类模块中,我需要将所有变量声明为Public,例如:
Public MotivID As Integer
Public MotivQuant As Integer
Public strMotivatorTitle() As String
Public strMotivatorDescriptor() As String
Run Code Online (Sandbox Code Playgroud)
但是响应最后两个变量的存在,运行给了我错误:
Compile error:
Constants, fixed-level strings, arrays, user-defined types and Declare statements are not allowed as Public members of object modules
Run Code Online (Sandbox Code Playgroud)
由于现有代码的限制,我需要在多个模块中创建和使用strMotivatorTitle和strMotivatorDescriptor变量。但我知道除非公开声明(而且我假设是在类模块中),否则我无法这样做。这就是我碰壁的地方。
任何帮助,不胜感激。自从获得博士学位以来,我并没有大量使用VB,所以我可能会被一些明显的事情绊倒...
解决方法是在初始化它们时将它们声明为Variant和ReDim作为字符串数组。
Public strMotivatorTitle As Variant
Public strMotivatorDescriptor As Variant
Run Code Online (Sandbox Code Playgroud)
例如,初始化为数组
Private Sub Class_Initialize()
ReDim strMotivatorTitle(0 To 9)
strMotivatorTitle(0) = "Foo"
strMotivatorTitle(1) = "Bar"
' etc
End Sub
Run Code Online (Sandbox Code Playgroud)
另一种方法,将您的字符串数组声明为,Private然后使用“属性获取”来访问它们
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
Run Code Online (Sandbox Code Playgroud)