无法在字段为对象的自定义类中为字段赋值

时间:2017-10-31 11:30:44

标签: excel-vba vba excel

我有自己的VBA自定义类。我创建了将保持对象工作表引用的字段:

Private ws As Worksheet

写属性:

Property Get TargetWorksheet() As Worksheet
    TargetWorksheet = ws
End Property
Property Set TargetWorksheet(ByRef newws As Worksheet)
    ws = newws
End Property

但是当我尝试分配值

Dim mylist As CustomPropertWS
mylist.TargetWorksheet = Sheet1
or
Set mylist.TargetWorksheet = Sheet1

宏总是抛出异常  "对象变量或未设置块变量"。如何设置包含类似对象的字段? 感谢。

1 个答案:

答案 0 :(得分:2)

对您的班级模块进行以下修改:

CustomPropertWS 类代码

Private ws As Worksheet

Property Get TargetWorksheet() As Worksheet
    Set TargetWorksheet = ws
End Property

Property Set TargetWorksheet(ByRef newws As Worksheet)
    Set ws = newws
End Property

你的Sub,它调用类代码:

TestClass 模块代码

Option Explicit

Sub TestClass()

Dim mylist As CustomPropertWS

Set mylist = New CustomPropertWS ' initiate the new class
'Set mylist.TargetWorksheet = Worksheets("Sheet1")
Set mylist.TargetWorksheet = Sheet1 ' <-- this method passes the worksheet's codename

Debug.Print mylist.TargetWorksheet.Name ' just for DEBUG

End Sub