Search code examples
vbaexceltextbox

How to make one code for 20 text boxes from 22 text boxes in total instead of 20 times the same


I have a group of 22 text boxes. The first 20 are numbers between 1 and 10 and textbox21 an textbox22 is the total of each group of 10. I have for textbox1 until textbox20 the same code, but how can I make this easier ?

Below you see the code I have for one of these textboxes.

Private Sub TextBox1_Change()
    korps(1) = 0
    korps1
    If TextBox1.Value = "" Then
                            TextBox1.SetFocus
                            Exit Sub
    End If
            If Not IsNumeric(TextBox1.Value) Then
                MsgBox "Sorry, only numbers allowed"
                TextBox1.Value = ""
                Exit Sub
            End If
    If TextBox1.Value = 0 Then TextBox1.Value = 10
    korps(1) = TextBox1.Value
    korps1
End Sub

Solution

  • If you follow the link in my comment you could create a class with the name txtBox and the following code

    Option Explicit
    
    Private WithEvents mTextBox As MSForms.Textbox
    
    Property Set Box(nBox As MSForms.Textbox)
        Set mTextBox = nBox
    End Property
    
    Private Sub mTextBox_Change()
    
        If mTextBox.Value = "" Then
            mTextBox.SetFocus
            Exit Sub
        End If
        If Not IsNumeric(mTextBox.Value) Then
            MsgBox "Sorry, only numbers allowed"
            mTextBox.Value = ""
            Exit Sub
        End If
        If mTextBox.Value = 0 Then mTextBox.Value = 10
    
    End Sub
    

    In the form you would need a code similar to the following code

    Option Explicit
    
    Dim colTxtBoxes As Collection
    
    Private Sub UserForm_Initialize()
    
    Dim m_txtBox As txtBox
    Dim ctl As MSForms.Control
    
        Set colTxtBoxes = New Collection
    
        For Each ctl In Me.Controls
    
            If ctl.Name = "TextBox21" Or ctl.Name = "TextBox22" Then
            Else
                If TypeName(ctl) = "TextBox" Then
                    Set m_txtBox = New txtBox
                    Set m_txtBox.Box = ctl
                    colTxtBoxes.Add m_txtBox
                End If
            End If
    
        Next ctl
    
    End Sub