要求在文本框中输入货币值(允许数字+小数点)
怎样判断是否输入了非法数值,比如讲字符串呢?

解决方案 »

  1.   

    Private Sub txt金额_KeyPress(KeyAscii As Integer)
        If (KeyAscii < Asc("0") Or KeyAscii > Asc("9")) And KeyAscii <> Asc(".") And KeyAscii <> 8 And KeyAscii <> 13 And KeyAscii <> 3 And KeyAscii <> 22 And KeyAscii <> 24 And KeyAscii <> 26 Then
            KeyAscii  = 0
            MsgBox "此处只能输入0到9的数字和小数点!", , "系统提示"
        Else
            KeyAscii  = KeyAscii
        End If
    End Sub
      

  2.   

    这个功能是容易实现,不过需要注意的地方很多,包括:
    1.是否允许粘贴
    2.Ctrl+V
    3.鼠标的右键粘贴
    4.键盘的右键菜单
    5.键盘的Shift+F10的右键菜单
    6.允许输入小数点,要注意是否允许输入多个小数点,小数点的位置等等~~
      

  3.   

    Private Sub Text1_Validate(Cancel As Boolean)
        If Not IsNumeric(Text1.Text) Then
            Cancel = True
            MsgBox "此处只能输入数字!",vbInformation,"系统提示"
        end if
    End Sub
      

  4.   

    cuizm(射天狼) 果然考虑周全
      

  5.   

    Validate是对有效性判断事件,不管是输入的或者粘贴的,只要不是数字,甚至小数点多于一个,都无法失去焦点的
      

  6.   

    Private Sub Text1_KeyPress(KeyAscii As Integer)
      If (KeyAscii < 48 Or KeyAscii > 57) And KeyAscii <> 46 Then KeyAscii = 0
    End Sub
      

  7.   

    其实这些方法都可以,最好是测试到录入的不是数值(小数点)或者判断.Text属性不是数值后立即回退一个字符,不然粘贴时候会报很多次错误出来
      

  8.   

    Private Sub Text1_KeyPress(KeyAscii As Integer)
      If  KeyAscii < 48 Or KeyAscii > 57 Then 
        KeyAscii = 0
      end if
    End Sub
      

  9.   

    viena(晓琴) 的我支持 厉害
      

  10.   

    直接在控件的属性里设置"data format"为“数字”就可以。
      

  11.   

    Private Sub Text1_Validate(Cancel As Boolean)
    If Not IsNumeric(Text1.Text) Then
            Cancel = True
            MsgBox "此处只能输入数字!", vbInformation, "系统提示"
        End If
    End Sub
    text1的validate事件完全可以达到你的要求
      

  12.   

    viena(晓琴) 的办法并不好~~~~
    在一般的程序中为了方便用户的操作,会设置一些快捷键,假如是一个对数据库操作的程序,用户在输入完成后,不移走焦点,直接使用快捷键保存的话,这个文本框就不会有失去焦点的事件发生。
    bell(bell)的程序考虑很周到,但是他没有阻止输入多个小数点的情况。Private Sub txt金额_KeyPress(KeyAscii As Integer)
        If (KeyAscii < Asc("0") Or KeyAscii > Asc("9")) And KeyAscii <> Asc(".") And KeyAscii <> 8 And KeyAscii <> 13 And KeyAscii <> 3 And KeyAscii <> 22 And KeyAscii <> 24 And KeyAscii <> 26 Then
            KeyAscii  = 0
            MsgBox "此处只能输入0到9的数字和小数点!", , "系统提示"
        Else
            If KeyAscii = asc(".") and instr(txt金额,".")<>0 then keyascii = 0 
            KeyAscii  = KeyAscii
        End If
    End Sub