简体   繁体   English

VBA-由于某种原因使用get / let不会设置属性

[英]VBA - working with get/let for some reason property won't set

Warning: I'm a newbie at VBA. 警告:我是VBA的新手。

I have the following class, named TestClass : 我有以下名为TestClass类:

Option Explicit
Private pName As String

Private Sub Class_Initialize()
    Name = "test_1"
End Sub
Public Property Get Name() As String
    Name = pName
End Property
Public Property Let Name(Value As String)
    pName = Value
End Property

I have a subroutine, that I wire up to a button click event, that looks like this: 我有一个子程序,它连接到一个按钮单击事件,如下所示:

Sub DisplayTestValue()

    Dim testClass As testClass

    With testClass
        MsgBox "default value: " & testClass.Name
    End With

    testClass.Name = "Tom"

    MsgBox "set to (Tom) value: " & testClass.Name

End Sub

I then click the button. 然后,我单击按钮。 It calls the subroutine. 它调用子例程。 I get the following error message: 我收到以下错误消息:

Run-time error '91':

Object variable or With block variable not set

The debugger stops on the following line of code: 调试器在以下代码行上停止:

MsgBox "default value: " & testClass.Name

The debugger tells me that testClass.Name is not set! 调试器告诉我未设置testClass.Name! I am very confused by this because I set a default value of "test_1" to the Name property in the class Initializer. 我对此感到很困惑,因为我在类Initializer中为Name属性设置了默认值“ test_1”。

Can someone please explain to me what I'm not doing correctly? 有人可以告诉我我做错了什么吗?

I found the answer 我找到了答案

I was not using the keyword New when instancing an object of my TestClass . 实例化TestClass的对象时,我没有使用关键字New

Bad: 坏:

Dim testClass As testClass

Good: 好:

Dim testClass As New testClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM