如何检查用户在文本框中输入的值是否为数字双精度?

时间:2019-02-05 17:03:23

标签: vba access-vba

我正在尝试检查用户是否在文本框中输入了数字值,并接受小数位。我们非常感谢您的帮助。

Private Sub textbox1_AfterUpdate()
If IsNumeric(textbox1.Value) = False Then
Me!textbox1.Undo
    MsgBox "only numbers are allowed"
Exit Sub
End If
Exit Sub

使用BeforeUpdate事件:

Private Sub textbox1_BeforeUpdate(Cancel As Integer)
If IsNumeric(textbox1.Value) = False Then
    MsgBox "only numbers are allowed"
Me!textbox1.Undo
Cancel = True
Exit Sub
End If
Exit Sub

我当前的代码根本不执行。我也在textbox1_BeforeUpdate事件中尝试过。请查看代码。

新代码:

Public Function IsValidKeyAscii(ByVal keyAscii As Integer, ByVal value As 
String) As Boolean
IsValidKeyAscii = (keyAscii = vbKeyDot And InStr(1, value, Chr$(vbKeyDot)) = 
0) Or (keyAscii >= vbKey0 And keyAscii <= vbKey9)
End Function

Private Sub textbox1_KeyDown(KeyCode As Integer, Shift As Integer)
If Not IsValidKeyAscii(KeyCode, textbox1.value) Then KeyCode = 0

End Sub

3 个答案:

答案 0 :(得分:2)

编写一个验证器函数(可以在其自己的KeyInputValidator类或模块中),因此您可以在需要的任何地方重复使用此逻辑,而不用为需要的每个数字文本框复制/粘贴它:

Option Explicit
Private Const vbKeyDot As Integer = 46

'@Description("returns true if specified keyAscii is a number, or if it's a dot and value doesn't already contain one")
Public Function IsValidKeyAscii(ByVal keyAscii As Integer, ByVal value As String) As Boolean
    IsValidKeyAscii = (keyAscii = vbKeyDot And InStr(1, value, Chr$(vbKeyDot)) = 0) Or (keyAscii >= vbKey0 And keyAscii <= vbKey9)
End Function

然后在文本框的KeyPress事件处理程序(假设这是MSForms文本框控件)中使用它来确定是否接受输入-因为该事件提供了MSForms.ReturnInteger对象,可以将该对象的Value属性设置为0来“吞下”按键:

Private Sub TextBox1_KeyPress(ByVal keyAscii As MSForms.ReturnInteger)
    If Not IsValidKeyAscii(keyAscii.Value, TextBox1.value) Then keyAscii.Value = 0
End Sub

这样,您无需撤消任何输入,也无需弹出任何令人讨厌的警告或消息框:该字段中的值保证为有效的数值!


编辑以上事件处理程序签名用于MSForms控件。看起来Access使用了不同的界面:

Private Sub TextBox1_KeyDown(KeyCode As Integer, Shift As Integer)

此处KeyCode被传递了ByRef,因此您可以直接对其进行更改。换句话说,这成为逻辑:

    If Not IsValidKeyAscii(KeyCode, TextBox1.value) Then KeyCode = 0

答案 1 :(得分:2)

您完全不应该将VBA用于此任务。

只需将字段格式属性设置为通用编号。这是确保用户只能在字段中输入数字的内置方式。

答案 2 :(得分:0)

您可以尝试使用失焦事件:

Private Sub TextBox1_LostFocus()
    Dim blnNumber As Boolean
    Dim strNumber As String

    strNumber = TextBox1.Value
    blnNumber = IsNumeric(strNumber)

    If Not blnNumber Then
        Me!TextBox1.Undo
        MsgBox "only numbers are allowed"
    Else
        'And, if you want to force a decimal.
        If InStr(strNumber, ".") < 1 Then
            Me!TextBox1.Undo
            MsgBox "only doubles are allowed"
        End If
    End If
End Sub

此外,检查在访问权限中列出的Textbox1元素。它是TextBox1的名称吗?或者是其他东西?  例如,在excel中,它的表示方式如下:=EMBED("Forms.TextBox.1",""),即使代码引用的名称是TextBox1。