2017-05-09 84 views
0

在我的用户表单中我想MsgBox如果文本框不包含数字或空。 这是我的代码,但在另一种情况下TextBox = ""空MsgBox对我来说,所以我的问题是空的TextBox。VBA用户窗体文本框只允许数字和空文本

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 
+0

什么'MsgBox“对不起,只允许输入数字,但是输入'”&.Value&“'。”'写入'''之间? –

+0

对不起,我不明白的味精:) –

+1

用我贴的代码替换你的MsgBox代码。运行你的代码,并告诉我们当你的文本框为空时MsgBox中的内容。 –

回答

2

为此使用Key Press事件。

Private Sub TB1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) 
    If Not IsNumeric(Chr(KeyAscii)) Then KeyAscii = 0 
End Sub 

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

0

由于您试图只允许“数字”和“空白”,那么下面的代码将提供您的需求。

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 
+0

你的答案当然值得一点解释。请参阅http://stackoverflow.com/help/how-to-answer。评论有助于创建可搜索的内容。 –

0

您可以使用AfterUpdate事件处理代替Change事件,可能还需要使用Exit事件,并取消退出如果用户输入一个无效的值:

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 
0

你可以等到用户完成输入然后测试该字段。

为便于使用,应将消息框替换为类似这样的标题和图标/图片enter image description here“必须在此输入一个数字。”

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

这允许用户输入请求数据,然后修复任何输入错误。这比每次他们犯错时停止它们要好。

活动从变更变为退出

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 

vbNullString测试也已更新。