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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5092662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:09:47  来源:igfitidea点击:

Set property of vba class with object reference

vba

提问by Iain Sproat

I have a class module, named Normal, in VBA with the following code:

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

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

This class is used by the following code:

此类由以下代码使用:

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

Also, if I change the code in the Normalclass module to:

另外,如果我将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

and the failing line to

和失败的线路

Norm.SetLine( Line )

I get an "Object does not support this property or method" error. What exactly am I doing wrong in both of these cases?

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

回答by mwolfe02

Try this:

尝试这个:

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

回答by Aleksey

Both properties must have "Set" keyword

两个属性都必须有“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

回答by Hamidreza.Kiani

Try this

尝试这个

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

回答by Ahmed Hossam

The Set statement is used to make a reference of an object to an object variable. You don't have to use the Set keyword, if you are dealing with primitive and native built-in types such as integer, double, string and so on. Here you are dealing with an object of type LineElement.

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