引用基础类实例

时间:2019-02-07 10:10:55

标签: excel vba

我在VBA-Excel中有一个Class1,带有一个名称变量和一个动态创建的Button,它是另一个类(cButton)的实例。我想在他的按钮单击事件中引用Class1实例,但是我无法使其正常工作。最小的工作示例:

Class1

Option Explicit
Dim myButton As cButton
Public ClassName As String

Sub createButton()
    Set myButton = New cButton
    Set myButton.ButtonObject = UserForm1.Controls.Add("Forms.CommandButton.1", "btn", True)
    myButton.ButtonName = "NiceButton"
End Sub

cButton类

Option Explicit
Public WithEvents ButtonObject As MSForms.CommandButton
Public ButtonName As String

Private Sub ButtonObject_Click()
    MsgBox ("This Button is called " & Me.ButtonName)
    'MsgBox ("This Button belongs to " & Me.Me.ClassName) 'Compile Error: Method or Data Member not found
End Sub

我创建一个实例,然后单击Userform1中的按钮:

Option Explicit
Dim myClass As Class1

Private Sub UserForm_Initialize()
    Set myClass = New Class1
    myClass.ClassName = "NiceClass"
    myClass.createButton
End Sub

当我单击按钮时,它正确显示了按钮名称(通过ButtonObject_Click中的Me.Name),但是我没有设法引用基础类实例来显示该类的名称。 (我知道,Me.Me.ClassName有点天真,但是我在任何地方都找不到解决方案)。如何引用按钮所属的Class1(myClass)的类实例?

预先感谢您的帮助。

0 个答案:

没有答案