我正在尝试检查用户是否在文本框中输入了数字值,接受小数位。任何帮助都非常感谢。
Private Sub textbox1_AfterUpdate()
If IsNumeric(textbox1.Value) = False Then
Me!textbox1.Undo
MsgBox "only numbers are allowed"
Exit Sub
End If
Exit Sub
使用之前更新事件:
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
您根本不应该使用此任务使用 VBA。
只需将字段格式属性设置为常规编号即可。这是确保用户只能在字段中输入数字的内置方法。
编写一个验证器函数(可以在它自己的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
您可以尝试使用失去焦点事件:
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
此外,选中您在 Access 中列出的 Textbox1 元素。 它的名字是文本框1吗?还是别的什么? 例如,在 excel 中,它表示如下:=EMBED("Forms.TextBox.1","")
即使代码引用的名称是 TextBox1。