VBA:在B类的属性中实例化A类

时间:2014-10-16 05:38:42

标签: excel vba oop

我是excel VBA OOP的初学者,需要帮助将带有属性的类实例放入另一个类的属性中。我有一种方法对我有意义,但不起作用。我不确定它只是一个简单的语法/结构错误,或者我是否完全错过了这个标记。这是一个简化的例子,它说明了我的问题:

  1. A类的属性具有字符串值。

  2. B类有一个属性,它包含一个A类实例,该属性接受一个字符串参数并将其传递给A类的属性。

  3. A类

    Private strProp As String
    
    Public Property Let Prop(sProp As String)
    
        strProp = sProp
    
    End Property
    

    B类

    Private clsA As New ClassA
    
    '''DIFFERENT ATTEMPTS OF THE SAME METHOD:
    
    Public Property Let ClassA(strNameA As String)
        clsA.Prop = strNameA
    End Property
    
    
    
    'Public Property Set ClassA(strNameA As String)
    '    clsA.Prop = strNameA
    'End Property
    
    
    
    'Public Property Set ClassA(strNameA As String)
    '
    '    Dim xClsA As ClassA
    '    Set xClsA = New ClassA
    '
    '    xClsA.name = "Foobar"
    '    clsA = xClsA
    '
    'End Property
    '
    
    
    Public Function message()
        msgbox(clsA.Prop)
    End Function
    

    模块(行动中的类)

    dim xClassB as ClassB
    set xClassB = new ClassB
    
    xClassB.ClassA("Foobar")
    xClassB.message   'should display Foobar
    

    我得到的错误:

    “我仍然遇到编译错误:同一属性的属性过程定义不一致或属性过程有可选参数,ParaArray或无效的set final参数”

1 个答案:

答案 0 :(得分:1)

A类

Private strProp As String

Public Property Let Prop(sProp As String)
    strProp = sProp
End Property

Public Property Get Prop() As String
    Prop = strProp 
End Property

ClassB的:

Private clsA As New ClassA

Public Property Set ClassA(strNameA As String)
    clsA.Prop = strNameA
End Property

Public Function message()
    msgbox(clsA.Prop)
End Function

...并在ClassA

中为Get添加Prop