读书人

请问:怎么在ComboBox中只能输入两位数

发布时间: 2012-01-18 00:23:26 作者: rapoo

请教:如何在ComboBox中只能输入两位数字?
我想在ComboBox中只能输入00至23,例如当输入3时就不能输入第2个数字了,
应该如何实现?
(ComboBox初始化时已经被添加了00至23共24个项目,可选择也可输入)

[解决办法]
在ComboBox的KeyPress事件中加如下代码:

if keyascii <asc( "0 ") or keyascii> asc( "9 ") then keyascii=0


[解决办法]
在ComboBox的KeyPress事件中加如下代码:

if keyascii <asc( "0 ") or keyascii> asc( "9 ") then keyascii=0:exit sub
if len(ComboBox.text)=2 then keyascii=0
[解决办法]
Private Sub Combo1_KeyPress(KeyAscii As Integer)
Dim i As Long
Dim str As String
If KeyAscii > = &H30 And KeyAscii <= &H39 Then
Combo1.SelText = " "

str = Combo1.Text & Chr(KeyAscii)
If Len(str) > 2 Then
KeyAscii = 0
End If

str = Left(str & "* ", 2)
For i = 0 To Combo1.ListCount - 1
If Combo1.List(i) Like str Then
Exit For
End If
Next

If i > = Combo1.ListCount Then
KeyAscii = 0
End If
End If
End Sub

Private Sub Form_Load()
Dim i As Long
For i = 0 To 23
Combo1.AddItem Format(i, "00 ")
Next
End Sub

[解决办法]
Private Sub cbo_KeyPress(KeyAscii As Integer)
If KeyAscii > = 48 And KeyAscii <= 57 Then '判断输入的是否是数字
If cbo.SelLength = 0 Then '判断是否有选中的字符
If Len(cbo.Text) > = 2 Then '判断组合框中的内容是否已是两位数(如果不写这句会输入多个0)
KeyAscii = 0
Else
If CInt(cbo.Text & Chr(KeyAscii)) > 23 Then KeyAscii = 0 '判断输入后数字是否已大于23
End If
End If
ElseIf Not (KeyAscii = 8) Then '判断输入的 不是 退格键(此判断不能少)
KeyAscii = 0
End If
End Sub
[解决办法]
if val(combo1.text)> 23 then combo1.text= "23 "

读书人网 >VB

热点推荐