vba - 将数组放入 class.property

标签 vba

我有一个具有以下属性的类:

Dim pBonds() as string

Private Property Get Bonds() As String
    Bonds = pBonds
End Property

Private Property Get Bond(index As Long) As String
    Bond = pBonds(index)
End Property

Private Property Let Bond(index As Long, strValue As String)
    If index > UBound(pBonds) Then ReDim Preserve pBonds(index)
    pBond(index) = strValue
End Property

当我尝试时:

Set o = New CBondBasket
   For k = LBound(arr) To UBound(arr)
       o.Bond(k) = arr(k)
   Next k

我收到错误未找到方法或数据成员

知道它来自哪里吗?

<小时/>

进行了更改

现在将它们标记为公共(public)并添加初始化和 byval(没有它又给我带来另一个错误)

Private Sub Class_Initialize()
    ReDim pBonds(0)
End Sub

Public Property Get Bonds() As String()
    Bonds = pBonds
End Property

Public Property Get Bond(index As Long) As String
    Bond = pBonds(index)
End Property

Public Property Let Bond(ByVal index As Long, ByVal strValue As String)
    If index > UBound(pBonds) Then ReDim Preserve pBonds(index)
    pBonds(index) = strValue
End Property

错误是:同一属性的属性过程的定义不一致,或者属性过程有可选参数、ParamArray 或无效的设置最终参数,有人可以帮助我吗?谢谢

最佳答案

您还需要初始化pBonds数组,否则第一次调用UBound时会出现错误:

主模块

Option Explicit

Sub testClass()

    Dim o As CBondBasket
    Dim k As Long
    Dim arr As Variant

    arr = Array(1, 2, 3, 4, 5)

    Set o = New CBondBasket
    For k = LBound(arr) To UBound(arr)
        o.Bond(k) = arr(k)
    Next k

    For k = LBound(o.Bonds) To UBound(o.Bonds)
        Debug.Print o.Bond(k)
    Next k

End Sub

CBondBasket 类

Private pBonds() As String

Private Sub Class_Initialize()
    ReDim pBonds(0)
End Sub

Public Property Get Bonds() As String()
    Bonds = pBonds
End Property

Public Property Get Bond(index As Long) As String
    Bond = pBonds(index)
End Property

Public Property Let Bond(index As Long, strValue As String)
    If index > UBound(pBonds) Then ReDim Preserve pBonds(index)
    pBonds(index) = strValue
End Property

关于vba - 将数组放入 class.property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9720018/

相关文章:

vba - 将 Excel-VBA 代码放入模块或工作表中?

python - 如何将Excel工作簿中的所有工作表保存为一个文本文件?

excel - ReferesToRange 给出运行时错误 '91' :

excel - 使用动态数组存储和粘贴值

VBA 循环遍历空列

VBA Word - 带有初始文件名的另存为对话框

vba - Excel 2013 中使用超出行 65536 的范围时出现问题

.addnew 的 Fieldvalue 参数中的 VBA Recordsets : Why does the way I declare my array,,有关系吗?

excel - 删除单元格内的值

python - 从 Python : macros may be disabled 运行 VBA 代码