代码如下:
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

解决方案 »

  1.   

    '功能:限制文本框只能输入数字或固定字符
    '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
      

  2.   

    ruikang(瑞康)兄,佩服佩服,你的做法好多了
      

  3.   

    wqb(啊喂)兄:过奖了,真是很汗颜,我们交个朋友吧,互相学习。
      

  4.   

    多谢ruikang(瑞康)兄和wqb(啊喂)和兄。