private sub text1_keypress(keyascii as integer)
dim I as integer
dim J as integerselect case  keyascii
case vbkeydelete,vbkeyback,vbkeyreturn
case else
  i=text1.selstart
  j=text1.sellength
  if not isnumeric(left(text1.text,i) & chr(keyascii) & mid(text1.text,i+j)) then
    keyascii=0
  end if
end select
end sub

解决方案 »

  1.   

    'This project needs a TextBox
    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
    Const GWL_STYLE = (-16)
    Const ES_NUMBER = &H2000&
    Public Sub SetNumber(NumberText As TextBox, Flag As Boolean)
        Dim curstyle As Long, newstyle As Long
        'retrieve the window style
        curstyle = GetWindowLong(NumberText.hwnd, GWL_STYLE)
        If Flag Then
           curstyle = curstyle Or ES_NUMBER
        Else
           curstyle = curstyle And (Not ES_NUMBER)
        End If
        'Set the new style
        newstyle = SetWindowLong(NumberText.hwnd, GWL_STYLE, curstyle)
        'refresh
        NumberText.Refresh
    End Sub
    Private Sub Form_Load()
        SetNumber Text1, True
        Me.Caption = "Now, try typing some letters into the textbox"
    End Sub
      

  2.   

    private sub text1_keypress(keyascii as integer)
    if keyascii<vbkey0 or keyascii>vbkey9 then
    msgbox ("请输入数字!!")
    text1.setfocus
    end if
    end sub
    这个方法有个缺点是:如果用户从别处copy 非数字,paste到文本框里,则这种方法检测不出来。
    还有一个方法是:设置text1控件下一个可获得焦点的控件的causesvalidation属性为true,则焦点移到该控件时可触发text1的validate事件
    Private Sub Text1_Validate(Cancel As Boolean)
    if not isnumeric(text1.text) then
    msgbox ("请输入数字!!")
    cancel=true
    text1.setfocus
    end if
    End Sub应该是这样,我昨天晚上刚从书上看到的。