将数组放入class.property

时间:2012-03-15 12:48:14

标签: 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

我收到错误Method or data member not found

知道它来自哪里?


进行了更改

现在将它们标记为公开,并添加了初始化和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或无效的set final参数可以帮助我吗?感谢

3 个答案:

答案 0 :(得分:2)

你还需要初始化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

答案 1 :(得分:1)

如果要将自己的类方法公开给自动化客户端,请将它们标记为Private

(你还需要parens来返回一个数组:Public

答案 2 :(得分:1)

class Category
  has_many :questions

class Question
 has_many :answers
 has_one :correct_answer #save as correct_answer_id
 attr_accessor :given_answer_id
 def correct_answered?
   given_answer_id == correct_answer_id
 end

class Answer
  belongs_to :question