类模块中的WithEvent无法从Excel VBA中的Let属性获取变量

时间:2018-03-20 22:38:04

标签: excel vba class

我想我在这里缺少一些简单的东西。尝试在Class模块中使用变量。让我们好好工作吧。但是如果我尝试在Class模块中的另一个子中使用该变量,我只得到一个值0。

班级模块clsCombobox

Public WithEvents ComboBox As MSForms.ComboBox
Public WithEvents ComboTextBox As MSForms.TextBox

Public Num As Long

Public Property Let Number(Value As Long)
    Num = Value
End Property

Public Property Get Number() As Long
    Number = Num
End Property

Private Sub ComboBox_Change()
    Me.ComboTextBox.Value = Num
    'this gives value of 0
End Sub

Userform模块

Dim obEvents as clsCombobox
Set obEvents = New clsCombobox
obEvents.Number = 52
MsgBox obEvents.Number 'this prints 52

设置ComboBox的子

Private Sub GroupCombobox()
Dim i As Long
Dim obEvents As clsCombobox

Set collCombobox = New Collection

For i = 1 To 5
    Set obEvents = New clsCombobox
    Set obEvents.ComboBox = Me.Controls("cbAbility" & i)
    Set obEvents.ComboTextBox = Me.Controls("tbAbility" & i & "Text")
    collCombobox.Add obEvents
Next i

End Sub

1 个答案:

答案 0 :(得分:3)

看起来你没有设定价值。我假设你的意思是在循环中这样做?也许没有i的价值,但在这里你可以看到这个想法......

For i = 1 To 5
    Set obEvents = New clsCombobox

    'Set the value here
    obEvents.Number = 52 ' 52 or whatever is needed as Number

    Set obEvents.ComboBox = Me.Controls("cbAbility" & i)
    Set obEvents.ComboTextBox = Me.Controls("tbAbility" & i & "Text")
    collCombobox.Add obEvents
Next i