Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii <> 13 Then
  Select Case KeyAscii
      Case Asc("-") '只能在最左
            If Text1.SelStart = 0 Then
              If Left(Text1.Text, 1) = "-" Then
                  KeyAscii = 0
                  Beep
              End If
            Else
              KeyAscii = 0
              Beep
            End If
        Case Asc(vbBack)
              '无变化,退格键不屏蔽
        Case Asc(" ") '32
            KeyAscii = 0
            If Text1.SelLength > 0 Then
                Text1.SelText = ""
            End If
        Case Asc(".") '46 Only One!!!!
            If InStr(Text1.Text, ".") Then
                KeyAscii = 0
            End If
        Case Is < Asc(0) '48
              KeyAscii = 0
        Case Is > Asc(9) '57
              KeyAscii = 0
  End Select
End Sub

解决方案 »

  1.   

    判断输入的是否是数字
    方法一:
    Private Sub Text1_KeyPress(KeyAscii As Integer)
    Key = Chr(KeyAscii)
    If KeyAscii <> 8 And Key < "0" Or Key > "9" Then
    MsgBox "请填入数字!"
    End If
    End Sub
    这个方法仍然可以输入字母,只是一个提示作用。
    方法二:
    限制输入(只可输入数字)
    KeyAscii = ValiText(KeyAscii, "0123456789", True)
    在模块中
    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) & Chr(13)
      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