VBA Compile Error: Can't Assign to Read-Only Property Returning Array from Custom Class Get Property

VBA Compile Error: Can't Assign to Read-Only Property Returning Array from Custom Class Get Property

我在 Get 属性 中遇到问题 VBA 中的自定义 class(Excel 2010 ).如果未给出索引参数,那么我的 Get 属性 应该 return 对 Class' 数组的引用(至少这是我的印象)。如果给出了索引,它应该 return 私有数组中给定索引中的值。

' Custom Class Properties
Private pMtbSheets() As String

'Get and Let Methods
Public Property Get MtbSheets(Optional index As Variant) As String()
    If IsMissing(index) Then
        ReDim MtbSheets(1 To UBound(pMtbSheets))
        MtbSheets = pMtbSheets()
    Else
        ReDim MtbSheets(1 To 1)
        MtbSheets(1) = pMtbSheets(index) '**Compiler error occures here**
    End If
End Property

感谢任何人能够提供的帮助

您需要一个临时数组来避免 MtbSheets(i) 被解释为 property/method/function 调用与数组访问之间的歧义:

ReDim temp(1 To 1) As String
temp(1) = pMtbSheets(index)
MtbSheets = temp 

编辑:我的回答当然行不通,您将需要使用 Alex K. 在他的回答中提到的临时数组。

就像您在 IsMissing() 分支中所做的那样 return 数组:

' Custom Class Properties
Private pMtbSheets() As String

'Get and Let Methods
Public Property Get MtbSheets(Optional index As Variant) As String()
    If IsMissing(index) Then
        ReDim MtbSheets(1 To UBound(pMtbSheets))
        MtbSheets = pMtbSheets()
    Else
        ReDim MtbSheets(1 To 1)
        MtbSheets = pMtbSheets(index)
    End If
End Property