使用对象引用设置vba类的属性

时间:2011-02-23 15:05:41

标签: vba

我在VBA中有一个名为Normal的类模块,代码如下:

Private mLine As LineElement

Public Property Get Line() As LineElement
    Line = mLine
End Property

Public Property Set Line(ByRef vLine As LineElement)
    mLine = vLine
End Property

以下代码使用此类:

Sub Run
    Dim Line As LineElement
    Set Line = New LineElement

    Dim Norm As Normal
    Set Norm = New Normal
    Set Norm.Line = Line 'FAILS here with "Object Variable or With Block Variable not set"'
End Sub

另外,如果我将Normal类模块中的代码更改为:

Private mLine As LineElement

Public Property Get Line() As LineElement
    Line = mLine
End Property

Public Sub SetLine(ByRef vLine As LineElement) 'changed from property to sub'
    mLine = vLine
End Property

和失败的行

Norm.SetLine( Line )

我得到“对象不支持此属性或方法”错误。在这两种情况下,我到底做错了什么?

4 个答案:

答案 0 :(得分:22)

试试这个:

Private mLine As LineElement

Public Property Get Line() As LineElement
    Set Line = mLine
End Property

Public Property Set Line(ByRef vLine As LineElement)
    Set mLine = vLine   'Note the added Set keyword in this line'
End Property

答案 1 :(得分:5)

两个属性都必须包含“Set”关键字

Private mLine As LineElement

Public Property Get Line() As LineElement
    Set Line = mLine 'Set keyword must be present
End Property

Public Property Set Line(vLine As LineElement) ' ByRef is the default in VBA
    Set mLine = vLine 'Set keyword must be present
End Property

答案 2 :(得分:1)

试试这个

Private mLine As new LineElement

Public Property Get Line() As LineElement
    Set Line = mLine
End Property

Public Property Set Line(ByRef vLine As LineElement)
    Set mLine = vLine
End Property

答案 3 :(得分:0)

Set语句用于将对象引用到对象变量。如果要处理原始和本机内置类型(如整数,双精度,字符串等),则不必使用Set关键字。在这里,您要处理LineElement类型的对象。

相关问题