文本框只允许输入数字
这是一种将文本框中的用户输入限制为仅数字字符的方法。
我已经创建了一个函数,并将其放到保存我的自定义函数的Class模块中。 要从任何要限制为数字输入的文本框控件的KEYPRESS事件中调用该函数。
您可能希望更改的唯一参数是最后一个参数,该参数确定小数点右边的位数。 此示例代码将输入限制为2个小数位。
KEYPRESS事件的代码
Dim myTextBox As TextBox
myTextBox = Me.ActiveControl
If myMiscClass.myNumOnly(e.KeyChar, Me.ActiveControl.Text, myTextBox.SelectionStart, 2) = True Then
e.Handled = True
Else
e.Handled = False
End If
If e.KeyChar = Chr(13) Then GetNextControl(Me.ActiveControl, True).Focus() 'Enter key moves to next control
功能代码(我把它放在它自己的类模块中(所以我只需要它一次),但是如果愿意,可以将它放在表单模块中。)
'*****************************************************
' myNumOnly()
' Purpose: Limits textbox input to numeric only
' Inputs: strKeyPress, key pressed
' strText, current text in textbox
' intPosition, current cursor position in textbox
' intDecimal, number of decimal places required
' ' Returns: False/True - discard keystroke/valid key
'*****************************************************
Shared Function myNumOnly(ByVal strKeyPress As String, ByVal strText As String, ByVal intPosition As Integer, ByVal intDecimal As Integer) As Boolean
Dim dot As Integer, ch As String
If Not Char.IsDigit(strKeyPress) Then myNumOnly = True
If strKeyPress = "-" And intPosition = 0 Then myNumOnly = False 'allow negative number
If strKeyPress = "." And strText.IndexOf(".") = -1 Then myNumOnly = False 'allow single decimal point
dot = strText.IndexOf(".")
If dot > -1 Then 'limit to set decimal places
ch = strText.Substring(dot + 1)
If ch.Length > (intDecimal - 1) Then myNumOnly = True
End If
If strKeyPress = Chr(8) Then myNumOnly = False 'allow Backspace
Return myNumOnly
End Function
随意问任何问题。
干杯,
翻译自: https://bytes.com/topic/visual-basic-net/insights/883122-function-only-allow-numeric-input-textbox
文本框只允许输入数字