仅允许在文本框中输入数字的功能

这是一种将文本框中的用户输入限制为仅数字字符的方法。
我已经创建了一个函数,然后将其放入保存自定义函数的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 
随意问任何问题。
干杯,

From: https://bytes.com/topic/visual-basic-net/insights/883122-function-only-allow-numeric-input-textbox

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值