使用 Class 和 WithEvents 检测文本框的变化

Using a Class and WithEvents to detect changes in textboxes

我在 VBE 中有一个用户表单,其中包含 12 个文本框(一年中的每个月各有一个)。还有一个额外的文本框,它应该显示前 12 个框中每个框中的值的总和,随着其他文本框中的值的变化而更新和重新计算自身。

非常感谢在实施此问题的解决方案方面提供的一些帮助。

我要实现的代码取自 post,网址为:

VBA: Detect changes in any textbox of the userform

但是我不确定在 class 下面的事件部分中放什么。

注意:这是我第一次尝试使用 classes,所以我只是在学习。

如果 Class1 是您的 class 模块的名称,Userform1 您的用户表单的名称,并且如果您希望所有文本框值的总和在 TextBox13 那么,

在您的 Class1 模块中插入

Private WithEvents txtbox As MSForms.TextBox
Dim ctlr As Control
Public sum As Integer

Public Property Set TextBox(ByVal t As MSForms.TextBox)
    Set txtbox = t
End Property

Private Sub txtbox_Change()
    sum = 0
    For Each ctlr In UserForm1.Controls
        sum = sum + Val(ctlr)
    Next ctlr
    UserForm1.TextBox13 = sum - Val(UserForm1.TextBox13)
End Sub

并在 UserForm1 模块中插入

Private myEventHandlers As Collection

Private Sub UserForm_Initialize()
    Dim txtbox As Class1

    Set myEventHandlers = New Collection

    Dim c As Control
    For Each c In Me.Controls
        If TypeName(c) = "TextBox" Then
            Set txtbox = New Class1

            Set txtbox.TextBox = c

            myEventHandlers.Add txtbox
        End If
    Next c
End Sub