Using a class, as follows from the answer above, is a good strategy for solving many controls in a compressed and elegant way:
1) I do not see problems when creating 25 events with 1 line, calling the general private procedure privateform, unless the number of controls is dynamic. This is KISS philosophy.
2) In general, I consider the Change event to be very alarming, because it performs the entire recount of each digit. It is more reasonable and moderate to do this using the Exit or Before upgrade event because it only recounts when deciding on the value. For example, Google Instant annoys me, trying to return answers, consuming resources, without the user asking a question.
3) There was a verification problem. I agree that you can avoid the wrong keys with the Change event, however, if you need to verify the data, you cannot know whether the user will continue to enter or if the data is ready for verification.
4). You must remember that the Change or Exit events do not force the user to go through text fields, so the system must be redefined and recounted when trying to exit the form without canceling.
The following code is simple but effective for static forms.
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean) Call AutoCalc(Cancel) End Sub Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean) Call AutoCalc(Cancel) End Sub ..... Private Sub TextBox25_Exit(ByVal Cancel As MSForms.ReturnBoolean) Call AutoCalc(Cancel) End Sub Private Function Valid ..... End Function Private Sub AutoCalc(Canc As Variant) If Not Valid() Then Canc=True ' Calculation End Sub
You depend on saving time, you can create a general VBA procedure to generate code for events related to controls in the form corresponding to the mask. This code may be in the draft sheet (it is safer to directly generate the code, which is a mistake in some versions of Excel), and not copy and paste into the form module.
Sub GenerateEvent(Form As String, Mask As String, _ Evento As String, Code As String) ' Form - Form name in active workbook ' Mark - String piece inside control name ' Evento - Event name to form procedure name ' Code - Code line inside event Dim F As Object Dim I As Integer Dim L As Long Dim R As Range Dim Off As Long Set F = ThisWorkbook.VBProject.VBComponents(Form) Set R = ActiveCell ' Destination code Off = 0 For I = 0 To F.Designer.Controls.Count - 1 If F.Designer.Controls(I).Name Like "*" & Mask & "*" Then R.Offset(Off, 0) = "Private Sub " & _ F.Designer.Controls(I).Name & "_" & Evento & "()" R.Offset(Off + 1, 0) = " " & Code R.Offset(Off + 2, 0) = "End Sub" Off = Off + 4 End If Next I End Sub Sub Test() Call GenerateEvent("FServCons", "tDt", "Exit", _ "Call AtuaCalc(Cancel)") End Sub