同一个用户表单上的多个文本框相同的macrosexcel vba

我目前正在制作一个用户表单,其中我有多个文本框。 所以现在我总共有15个文本框,每个文本框只能包含数值。 我现在得到的每个文本框的代码是:

Private Sub TextBox1_Change() If TypeName(Me.ActiveControl) = "TextBox" Then With Me.ActiveControl If Not IsNumeric(.Value) And .Value <> vbNullString Then MsgBox "Sorry, only numbers allowed" .Value = vbNullString End If End With End If End Sub Private Sub TextBox2_Change() If TypeName(Me.ActiveControl) = "TextBox" Then With Me.ActiveControl If Not IsNumeric(.Value) And .Value <> vbNullString Then MsgBox "Sorry, only numbers allowed" .Value = vbNullString End If End With End If End Sub . . . Private Sub TextBox15_Change() If TypeName(Me.ActiveControl) = "TextBox" Then With Me.ActiveControl If Not IsNumeric(.Value) And .Value <> vbNullString Then MsgBox "Sorry, only numbers allowed" .Value = vbNullString End If End With End If End Sub 

我现在做的方式现在感觉有点马虎,因为我复制每个文本框相同的代码。 我的问题是,是否可以合并这些例程,以便我只需要一个代码来处理TextBoxes?

亲切的问候和感谢,

莫里斯

简单的例子:

添加一个新的类模块到您的项目,并将其重命名为NumericTextbox 。 将这个代码粘贴到它:

 Option Explicit Private WithEvents tb As MSForms.TextBox Public Property Set TextControl(t As MSForms.TextBox) Set tb = t End Property Private Sub tb_Change() With tb If Not IsNumeric(.Value) And .Value <> vbNullString Then MsgBox "Sorry, only numbers allowed" .Value = vbNullString End If End With End Sub 

现在在你的用户表单中,添加下面的代码:

 Option Explicit Private colTBs As Collection Private Sub UserForm_Initialize() Dim ctl As MSForms.Control Dim oHandler As NumericTextbox Set colTBs = New Collection For Each ctl In Me.Controls If TypeOf ctl Is MSForms.TextBox Then Set oHandler = New NumericTextbox Set oHandler.TextControl = ctl colTBs.Add oHandler End If Next ctl End Sub 

你去了

我只是将文本框作为parameter passing给我的函数,如下所示:

表单代码

 Private Sub TextBox1_Change() test Me.TextBox1 End Sub Private Sub TextBox2_Change() test Me.TextBox2 End Sub 

模块代码:

 Sub test(textbox As Object) With textbox If Not IsNumeric(.Value) And .Value <> vbNullString Then MsgBox "Sorry, only numbers allowed" .Value = vbNullString End If End With End Sub 

简单的方法是为每个文本框设置一个处理程序,以便在每个单独的操作之后执行特定的过程,我build议将您的过程分离为以下

 Private Sub checkValue() With Me.ActiveControl If Not IsNumeric(.Value) And .Value <> vbNullString Then MsgBox "Sorry, only numbers allowed" .Value = vbNullString End If End With End Sub 

然后从每个textbox_change()过程调用该子