代码如下:
Option ExplicitPrivate Sub Combo1_Change()
CheckValue Combo1, 5
End Sub
Private Sub CheckValue(obj As ComboBox, lens As Integer)
With obj
'只能输入数字
If isN(.Text) = False Then '不是数字
.Text = Mid(.Text, 1, Len(.Text) - 1) '去掉刚输入的一位
.SetFocus
Beep
Exit Sub
End If
'不能超过长度
If Len(.Text) > lens Then
.SelStart = 1
.SelLength = Len(.Text)
.SetFocus
End If
End With
End Sub
Private Function isN(str As String) As Boolean
Dim i As Integer
Dim lens As Integer
Dim strtemp As String
lens = Len(str)
For i = 1 To lens
strtemp = Mid(str, i, 1)
If Asc(strtemp) > 58 Or Asc(strtemp) < 48 Then
isN = False
Exit Function
End If
Next
isN = True
End Function
Option ExplicitPrivate Sub Combo1_Change()
CheckValue Combo1, 5
End Sub
Private Sub CheckValue(obj As ComboBox, lens As Integer)
With obj
'只能输入数字
If isN(.Text) = False Then '不是数字
.Text = Mid(.Text, 1, Len(.Text) - 1) '去掉刚输入的一位
.SetFocus
Beep
Exit Sub
End If
'不能超过长度
If Len(.Text) > lens Then
.SelStart = 1
.SelLength = Len(.Text)
.SetFocus
End If
End With
End Sub
Private Function isN(str As String) As Boolean
Dim i As Integer
Dim lens As Integer
Dim strtemp As String
lens = Len(str)
For i = 1 To lens
strtemp = Mid(str, i, 1)
If Asc(strtemp) > 58 Or Asc(strtemp) < 48 Then
isN = False
Exit Function
End If
Next
isN = True
End Function
解决方案 »
- VB照相功能要怎样实现?
- 求助!!急!!有难度,高手进!
- VB下如何给SQL server里“是\否”字段付值或更改值?
- 在win98系統裡.怎樣獲得某個NT網域用戶所屬的群組?
- 求救各位朋友:我在外地调程序.遇到点问题.我现在在网吧找到一个我需要的源代码.可是网吧没有VB.求朋友了.
- 如何做错误处理?在线等待!!
- 关于打包的问题,100分求助!!!!!!!!
- 谁有给手机发短信息的DLL OR OCX
- 关于SQL的很有趣的问题!!大家可不要错过哟!
- DBGRID控件CLICK为何得到前一次的记录,如何得到当前记录。
- 撒分啦,请大家都来推荐优秀的vb站点,推荐者有分~!(***分数还会加***)
- vb中如何判断点击了最小化按钮
'KeyIn----键盘输入字符的ascii码,ValidateString 限定可以输入的字符
'Editable-----能否使用 BackSpace键
'若输入的字符是ValidateString中字符,则不变;否则不允许输入
Public Function Valitext(KeyIn As Integer, ValidateString As String, Editable As Boolean) As Integer
Dim ValidateList As String
Dim KeyOut As Integer
If Editable = True Then
ValidateList = UCase(ValidateString) & Chr(8)
Else
ValidateList = UCase(ValidateString)
End If
If InStr(1, ValidateList, UCase(Chr(KeyIn)), 1) > 0 Then
KeyOut = KeyIn
Else
KeyOut = 0
Beep
End If
Valitext = KeyOut
End Function
在KeyPress事件中调用以上函数可以限制只能输入数字或固定字符,例如
Private Sub Combo1_KeyPress(KeyAscii As Integer)
If Len(Combo1.Text) < mLength Then'mLength是你限制的长度
KeyAscii = Valitext(KeyAscii, "0123456789", True)
Else
If Combo1.SelLength = mLength Then
KeyAscii = Valitext(KeyAscii, "0123456789", True)
Else
KeyAscii = 0
End If
End If
End Sub
这样,当用右键弹出菜单中的粘贴时,会产生问题。为此添加
Private Sub Combo1_Change()
Dim strTmp As String, i As Long
If Len(Combo1.Text) > 2 Then
Combo1.Text = Left(Combo1.Text, 2)
End If
If Len(Combo1.Text) > 0 Then
For i = 1 To Len(Combo1.Text)
If Asc(Mid(Combo1.Text, i, 1)) < 58 And Asc(Mid(Combo1.Text, i, 1)) > 47 Then
strTmp = strTmp & Mid(Combo1.Text, i, 1)
End If
Next i
Combo1.Text = strTmp
End If
End Sub