如何在类模块中使用公共variables?

我正在使用一个类模块来使保存button的集合都做同样的事情。 但是当我试图让他们运行一个需要一个variables的子我无法获得传递给他们的variables。

使用@ Teasel关于属性的build议进行编辑。 问题似乎是Let属性不允许我从Module1设置variables。

1类

Public WithEvents SaveBtn As MSForms.CommandButton Dim currentrow As Long Private Sub SaveBtn_Click() SendMessage `Even if I just have it Msgbox currentrow it returns 0 End Sub Property Let GetRow(myrow As Long) currentrow = myrow End Property Property Get GetRow() As Long GetRow = currentrow End Property 

模块1

 `Trying to send the value into the Class using Let Private Sub SendRow_Click() Module1.GetRow = 22 End Sub `Trying to Get the value back from the Class Public Sub SendMessage() Dim therow As Long therow = Module1.GetRow `I get the "Method or Data Member not found" error in the line above MsgBox therow End Sub 

UserForm1

 `This part works fine Dim colSaveButtons As New Collection Private Sub UserForm_Initialize() Dim i As Long Dim ctl As MSForms.Control Dim obEvents As Class1 For Each ctl In Me.Controls If TypeOf ctl Is MSForms.CommandButton Then For i = 0 To 5 If ctl.Name = "btnSavePage" & i Then Set obEvents = New Class1 Set obEvents.SaveBtn = ctl colSaveButtons.Add obEvents End If Next End If Next ctl End Sub 

添加一个“CurrentRow”字段到你的类模块:

 Public WithEvents SaveBtn As MSForms.CommandButton Public CurrentRow As Long '<< add this Private Sub SaveBtn_Click() SendMessage CurrentRow End Sub 

在你的循环中:

 ... If ctl.Name = "btnSavePage" & i Then Set obEvents = New Class1 obEvents.CurrentRow = 10 'or whatever... Set obEvents.SaveBtn = ctl colSaveButtons.Add obEvents End If ... 

和你的SendMessage方法:

 Public Sub SendMessage(CurrentRow As Long) MsgBox "This works" End Sub 

你可以使用两种不同的方式来实现这一点。


1.公共财产

要简单地访问你的variables的值,你需要一个Get属性,并设置它的值,你需要一个Let属性。

在你的模块中:

 'Your module private variable Dim nameOfYourModuleVariable As String ... 'Set property to assign a value to your variable Public Property Let nameOfYourProperty(value As String) nameOfYourModuleVariable = value End Property 'Get property to return the value of your variable Public Property Get nameOfYourProperty() As String nameOfYourProperty = nameOfYourModuleVariable End Property 

你可以像这样使用它:

 'Set the value MyModule.nameOfYourProperty = "foo" 'Get the value MyModule.nameOfYourProperty 

我强烈build议使用属性来做这样的事情,但是你也可以简单地将你的variables设置为public ,如第2点所示。


2.公共variables

定义你的variables是公开的,所以你可以从任何地方访问它。

在你的模块中:

 Public nameOfYourVariable As String 

从另一个模块获取或设置值:

 'Set the value MyModule.nameOfYourVariable = "foo" 'Get the value MyModule.nameOfYourVariable