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

Iai*_*oat 16 vba

我有一个名为NormalVAC 的类模块,代码如下:

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
Run Code Online (Sandbox Code Playgroud)

以下代码使用此类:

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
Run Code Online (Sandbox Code Playgroud)

另外,如果我将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
Run Code Online (Sandbox Code Playgroud)

和失败的路线

Norm.SetLine( Line )
Run Code Online (Sandbox Code Playgroud)

我得到一个"对象不支持此属性或方法"错误.在这两种情况下,我究竟做错了什么?

mwo*_*e02 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
Run Code Online (Sandbox Code Playgroud)

  • 噢哦这么简单!谢谢您的帮助.(我讨厌VBA编辑器,它不能为像这样的简单事情提供更多帮助) (4认同)

Ale*_*sey 5

这两个属性都必须具有“设置”关键字

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
Run Code Online (Sandbox Code Playgroud)