VBA用户窗体文本框只允许数字和空白文本

在我的用户表单中,如果TextBox不包含Numbers或空,我想要MsgBox。 这是我的代码,但在另一种情况下,当TextBox = ""清空MsgBox对我来说,所以我的问题是空的TextBox。

 Private Sub TB1_Change() If TypeName(Me.TB1) = "TextBox" Then With Me.ActiveControl L12.Caption = Val(TB1.Text) * Val(TB2.Text) 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 TB1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) If Not IsNumeric(Chr(KeyAscii)) Then KeyAscii = 0 End Sub 

如果不是数字,此过程将忽略您input的任何内容,但您可以修改条件和输出。 例如,您可能允许input小数点,或者您可能希望显示一个消息框 – 可能仅在第二次尝试时才显示。

您可以使用AfterUpdate事件处理程序而不是 Change事件,也可能需要使用Exit事件并在用户input无效值时取消退出:

 Option Explicit Private Sub TB1_AfterUpdate() 'Check whether the value is numeric or empty: If Not IsValNumeric(Me.TB1.Value) Then MsgBox "Sorry, only numbers allowed" Me.TB1.Value = vbNullString Else: 'Do something... MsgBox val(TB1.Text) * val(TB2.Text) End If End Sub Private Sub TB1_Exit(ByVal Cancel As MSForms.ReturnBoolean) 'Prevents the user from EXIT the TextBox if value is not numeric/empty Cancel = Not IsNumeric(Me.TB1.Value) End Sub Private Function IsValNumeric(val$) As Boolean Dim ret As Boolean 'check for numeric value only and allow empty value as a zero value ret = IsNumeric(val) Or Len(val) = 0 IsValNumeric = ret End Function 

您可以等待,直到用户完成input,然后testing该字段。

为了便于使用,消息框应该replace为标题和图标/图片 在这里输入图像说明 “必须在这里input一个数字。”

当input不正确时,这些将显示在文本框旁边。 然后在input更正时隐藏。 提交表格可以被阻止,直到所有的错误得到纠正。

这允许用户input请求数据,然后修复任何input错误。 每次他们犯错都要停下来。

事件从“ 更改”更改为“ 退出”

 Private Sub TB1_Exit(ByVal Cancel As MSForms.ReturnBoolean) If TypeName(Me.TB1) = "TextBox" Then With Me.ActiveControl L12.Caption = Val(TB1.Text) * Val(TB2.Text) If Not IsNumeric(.Value) Or .Value = vbNullString Then MsgBox "Sorry, only numbers allowed" .Value = vbNullString End If End With End If End Sub 

vbNullStringtesting也被更新了。

既然你只是试图让“数字”和“空白”,那么下面的代码将提供您的需求。

 Private Sub TB1_Change() if IsNumeric(Me.TB1.Value) = True or Me.TB1.Value = vbNullString then 'Good data, nothing to MSG Else MsgBox "Your input data is not valid" Endif End Sub