我正在使用类模块来创建一组保存按钮,它们都做同样的事情。但是当我试图让它们运行一个需要变量的子时,我无法将变量传递给它们。
使用@ Teasel关于属性的建议进行编辑。问题似乎是Let Property不允许我从Module1设置变量。
的Class1
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
答案 0 :(得分:1)
您可以使用两种不同的方法来实现这一目标。
<强> 1。公共财产
要简单访问变量的值,您需要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
我强烈建议您使用属性来执行此类操作,但您也可以将变量设置为public
,如第2点所示。
<强> 2。公共变量
将您的变量定义为公开,以便您可以从任何地方访问它。
在你的单元中:
Public nameOfYourVariable As String
从另一个模块中获取或设置值:
'Set the value
MyModule.nameOfYourVariable = "foo"
'Get the value
MyModule.nameOfYourVariable
答案 1 :(得分:1)
在您的班级模块中添加“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