求问: 怎么样实现对textbox控制它只能输入数字,其它的输入不让用户输入呢??

reminious 2004-04-20 07:48:35
怎么样实现对textbox控制它只能输入数字,其它的输入(如 :字符)不让用户输入呢??
...全文
50 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
chinaJeff 2004-04-20
  • 打赏
  • 举报
回复
不好意思,上面有错误应该是
If (InStr(strvalid, Chr(KeyAscii)) = 0) Then
KeyAscii = 0
'如果输入的字符在已定义的字符串中没有出现,就屏蔽掉
End If
chinaJeff 2004-04-20
  • 打赏
  • 举报
回复
我来写一段
private sub Text1_Keypress(Keyascii as integer)
Dim strvalid As String
strvalid = "0123456789"
'上面的字符串就是你允许用户输入的字符,还可以加入"."和"-"
If (InStr(strvalid, Chr(KeyAscii)) <> 0) Then
KeyAscii = 0
'如果输入的字符在已定义的字符串中出现了,就屏蔽掉
End If
End sub

这样写主要是方便添加要屏蔽的字符,实际要用还得对一些控制字符,像DEL,BACK之类做出
判断,最后还得屏蔽ctrl+v和鼠标右键的复制。
monorail0421 2004-04-20
  • 打赏
  • 举报
回复
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii < 48 And KeyAscii <> 8 Or KeyAscii > 57 Then KeyAscii = 0
End Sub
hebangxm 2004-04-20
  • 打赏
  • 举报
回复
楼上的不错,同意,支持一下
leolan 2004-04-20
  • 打赏
  • 举报
回复
'在Text1_KeyPress事件裡判斷:

Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii <> vbKeyBack And KeyAscii <> Asc("-") And KeyAscii <> Asc(".") Then
If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
KeyAscii = 0
End If
End If
End Sub
reminious 2004-04-20
  • 打赏
  • 举报
回复
Thanks all of all!
Check!!!
道素 2004-04-20
  • 打赏
  • 举报
回复
我也提供三种
api方法
Option Explicit
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Const GWL_STYLE = (-16)
Private Const ES_NUMBER = &H2000&

Public Function NumbersOnly(tBox As TextBox)

Dim DefaultStyle As Long

DefaultStyle = GetWindowLong(tBox.hWnd, GWL_STYLE)

NumbersOnly = SetWindowLong(tBox.hWnd, GWL_STYLE, DefaultStyle Or ES_NUMBER)

End Function

直接校验,考了小数点
Public Sub VerifyFloat(KeyAscii As Integer, ByVal sText As String)
If KeyAscii = 8 Or KeyAscii = 13 Or (KeyAscii > 47 And KeyAscii < 58) Then
Exit Sub
ElseIf KeyAscii = 46 Then
If Not IsNumeric("0" & sText & Chr(KeyAscii)) Then KeyAscii = 0
Else
KeyAscii = 0
End If
End Sub

正则表达式
Private Sub Text1_KeyPress(KeyAscii As Integer)
If Not (Chr(KeyAscii) Like "[0-9]") Then KeyAscii = 0
End Sub

以上没有考虑用户粘贴的情况

1,453

社区成员

发帖
与我相关
我的任务
社区描述
VB 控件
社区管理员
  • 控件
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧