Excel 有没有办法阻止文本框接受信件?

Excel 有没有办法阻止文本框接受信件?,excel,vba,Excel,Vba,我有以下代码,如果您键入的内容不是数字,则会显示错误消息: Private Sub TextBox3_Change() If Not IsNumeric(TextBox3.Value) Then MsgBox "Only digits (0-9) allowed." Cancel = True End If End Sub 问题是,如果我在框中键入一封信,它会给我错误消息,但仍会将信写入框中。我希望代码能够完全阻止非数字输入。您可以清除文本框中的

我有以下代码,如果您键入的内容不是数字,则会显示错误消息:

Private Sub TextBox3_Change()
    If Not IsNumeric(TextBox3.Value) Then
        MsgBox "Only digits (0-9) allowed."
        Cancel = True
    End If
End Sub

问题是,如果我在框中键入一封信,它会给我错误消息,但仍会将信写入框中。我希望代码能够完全阻止非数字输入。

您可以清除文本框中的值

Private Sub TextBox3_Change()
    If Not IsNumeric(TextBox3.Value) Then
        MsgBox "Only digits (0-9) allowed."
        TextBox3.Value = ""
        Cancel = True
    End If
End Sub
或者,如果不想删除所有内容,可以删除最后输入的字符

Private Sub TextBox3_Change()
    If Not IsNumeric(TextBox3.Value) Then
        MsgBox "Only digits (0-9) allowed."
        TextBox3.Value = Left(TextBox3.Value,Len(TextBox3.Value) - 1)
        Cancel = True
    End If
End Sub

您可以使用按键事件首先停止任何非数字输入

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

If Not (KeyAscii >= 48 And KeyAscii <= 57) Then
    KeyAscii = 0
End If

End Sub
Private Sub TextBox1\u按键(ByVal keyscii作为MSForms.ReturnInteger)

如果不是(keyscii>=48且keysciiu可以使用keydown事件

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
   If Not IsNumeric(Chr(KeyCode)) Then
      KeyCode = 0
   End If
End Sub

您应该使用KeyPress事件

Private Sub TextBox3_KeyPress(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox3.KeyPress
    Dim sKeys As String = "1234567890"
    If Not sKeys.Contains(e.KeyChar.ToString()) Then e.Handled = True
End Sub

这是在用户窗体上吗?@SJR,是的,它是ActiveX。请注意,
IsNumeric
将为0-9以外的字符返回True。在此特定上下文中,尾随空格、尾随
+
-
符号、十进制分隔符和千位分隔符都将被IsNumeric接受。其他组合也可以作为一个整体工作(例如,
10e5
)但是在这种情况下,当一个字符一个字符地构建时会失败(例如,
10e
失败)@Steven Carlson:谢谢!不过,在输入字母之前,我想保留文本框中以前的任何数字。