在多个其他文本框中的任何一个更新后更新文本框的值

Update value of TextBox after any of multiple other TextBoxes have updated

我正在为我当地的台球厅开发联赛经理。

我创建了一个用户窗体来输入分数,我正在寻找一种更简单的方法来编写我的控件。
我有一个文本框来显示用户窗体中其他文本框中包含的值的总和。
如果任何文本框更改或更新,是否有办法更新此总和?

我的研究指出了对文本框使用 class 的方向,但我读到的是 WithEvents 修饰符不支持更改或 Before/After 更新。
我还没有找到解决我的问题的示例,或者更确切地说是仅适用于我想分组的文本框而不适用于所有文本框的示例。
我可以为每个文本框编写一个子例程(如下所示),但我觉得还有更有效的方法。

Private Sub txtPlayer1_1_Score6_AfterUpdate()
    txtPlayer1_1_Total.Value = CInt(txtPlayer1_1_Score1.Value) + _
                               CInt(txtPlayer1_1_Score2.Value) + _
                               CInt(txtPlayer1_1_Score3.Value) + _
                               CInt(txtPlayer1_1_Score4.Value) + _
                               CInt(txtPlayer1_1_Score5.Value) + _
                               CInt(txtPlayer1_1_Score6.Value)
    
End Sub

下面是一个在 class 模块中使用 Change 事件的示例。它假定用户窗体被命名为 UserForm1,因此相应地更改名称。此外,您可能希望根据自己的喜好更改代码的行为方式,但至少这是一个开始。

首先,在 Visual Basic 编辑器中,插入一个 class 模块(Visual Basic 编辑器 >> 插入 >> Class 模块)。然后,在属性 window (F4) 下,将您的 class 命名为 clsTextBox。然后,将以下代码放入 class...

的代码模块中
Option Explicit

Public WithEvents tb As MSForms.textBox

Private Sub tb_Change()
    Dim textboxCollection As Collection
    Dim textBox As clsTextBox
    Dim total As Long
    Set textboxCollection = UserForm1.getTextBoxCollection()
    total = 0
    For Each textBox In textboxCollection
        If Len(textBox.tb.Value) > 0 Then
            If IsNumeric(textBox.tb.Value) Then
                total = total + textBox.tb.Value
            Else
                With textBox.tb
                    .SetFocus
                    .SelStart = 0
                    .SelLength = Len(.Value)
                End With
            End If
        End If
    Next textBox
    UserForm1.txtPlayer1_1_Total.Value = total
End Sub

然后,将以下代码放入用户窗体的代码模块中...

Option Explicit

Dim m_textboxCollection As New Collection

Private Sub UserForm_Initialize()
    Dim ctrl As MSForms.Control
    Dim textBox As clsTextBox
    For Each ctrl In Me.Controls
        If InStr(1, ctrl.Name, "Score", vbTextCompare) > 0 Then
            Set textBox = New clsTextBox
            Set textBox.tb = ctrl
            m_textboxCollection.Add textBox
        End If
    Next ctrl
End Sub

Public Property Get getTextBoxCollection()
    Set getTextBoxCollection = m_textboxCollection
End Property

不过,我建议您对总数使用标签而不是文本框,这样用户就无法更改其值。

希望对您有所帮助!