我使用一个类模块来使一个保存按钮集合都做同样的事情。但是,当我试图让它们运行一个需要变量的子程序时,我无法将变量传递给它们。
使用@Teasel关于属性的建议进行编辑。问题似乎在于,Let属性不允许我从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 PropertyModule1
`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 SubUserForm1
`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发布于 2017-11-27 23:58:25
在类模块中添加"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发布于 2017-11-27 06:33:22
您可以使用两种不同的方法来实现这一点。
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.nameOfYourVariablehttps://stackoverflow.com/questions/47503558
复制相似问题