使用数组VBA初始化对象

Mal*_*red 3 arrays oop excel vba excel-vba

我正在尝试创建一个包含数组的类,我遇到了为它创建类的问题......

类:

Private pST(0 To 2) As String

Public Property Get ST() As String
   ST() = pST()
End Property
Public Property Let ST(value() As String)  '<---- ERROR HERE
   pST() = value()
End Property
Run Code Online (Sandbox Code Playgroud)

代码运行:

Sub test()

   Dim foo As cPurchaseOrder
   Set foo = New cPurchaseOrder

   foo.ST(0) = "test"

   Debug.Print foo.ST(0)

End Sub
Run Code Online (Sandbox Code Playgroud)

错误:

编译错误:

相同属性的属性过程的定义不一致,或者属性过程具有可选参数,ParamArray或无效的Set final参数.

问题:

如何使用数组作为变量正确初始化类?

编辑: 关于Mat的Mug响应

课程已更改:

Private pST As Variant

Public Property Get STContent(ByVal index As Long) As String
    STContent = pST(index)
End Property

Public Property Let STContent(ByVal index As Long, ByVal value As String)
    pST(index) = value
End Property

Private Sub Class_Initialize()
   ReDim pST(0 To 2)
End Sub
Run Code Online (Sandbox Code Playgroud)

代码运行测试:

Sub test()

   Dim foo As cPurchaseOrder
   Set foo = New cPurchaseOrder

   foo.STContent(0) = "test" '<--- Type mismatch here

   Debug.Print foo.STContent(0)

End Sub
Run Code Online (Sandbox Code Playgroud)

Mat*_*don 5

您的getter需要返回一个String()数组以使类型保持一致:

Public Property Get ST() As String()
Run Code Online (Sandbox Code Playgroud)

但是,我不建议公开这样的数组.首先因为分配类型化数组非常痛苦,其次是因为setter(Property Let)实际上是在这里作弊:

Public Property Let ST([ByRef] value() As String)
Run Code Online (Sandbox Code Playgroud)

除非你ByVal明确指定,否则总是ByRef在VBA中传递一个参数...除了这个怪癖之外Property Let- RHS/value参数总是ByVal在运行时传递.

数组只能通过ByRef.

因此,获取(或实际分配)整个数组的属性没有多大意义.

一种更好的方法是封装数组(我将其设为一个Variant),并通过索引属性公开其内容(而不是数组本身):

Private internal As Variant 'String array

'...

Public Property Get Content(ByVal index As Long) As String
    Content = internal(index)
End Property

Public Property Let Content(ByVal index As Long, ByVal value As String)
    internal(index) = value
End Property
Run Code Online (Sandbox Code Playgroud)