限制用户仅在vb6中的文本框中插入数字

时间:2015-02-28 14:06:19

标签: vb6

如何创建一个文本框,我的应用程序用户只能在其中插入一个浮点数? (我的意思是一个浮点数,如:123,4567一个整数,只能在它的数字之间插入一个点。)

我的方法是在keypress事件中使用keyascii,如下面的代码:

Private Sub Text1_KeyPress(KeyAscii As Integer) 
   Select Case KeyAscii
   Case 8   'For making use of BackSpace key on keyboard impssibility
   Case 46  'Can inserting dot as point of number but just 1 of it... 
       b = false
       For i = 1 To Len(Text1.Text)
            a = Mid(Text1.Text, i, 1)
            If a="." Then b = True
       Next
       If b = False Then 
            KeyAscii = 46
       Else
            KeyAscii = 27 'or"Beep" 4 ereasing the inserted key as Escape
       End if
    Case 48 To 57  'For allowing to insert of digits 0 to 9
    Case else
       Beep  'or "KeyAscii = 27" for doing Nothing app As aborting key
    End select
End Sub

你知道这么多小代码还是有其他方法请说出来。

1 个答案:

答案 0 :(得分:0)

更像是什么:

Option Explicit

Private DecimalPt As String

Private Sub Form_Load()
    DecimalPt = Mid$(CStr(1.1), 2, 1)
End Sub

Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)
    Dim Text As String
    Dim SelStart As Long
    Dim Char As Long
    Dim GotDecimalPt As Boolean

    With Text1
        Text = .Text
        If Len(Text) > 0 And Not IsNumeric(Text) Then
            SelStart = .SelStart
            If Left$(Text, 1) = "-" Then
                Char = 2
            Else
                Char = 1
            End If
            Do While Char <= Len(Text)
                Select Case Mid$(Text, Char, 1)
                    Case DecimalPt
                        If GotDecimalPt Then
                            Text = Left$(Text, Char - 1) & Mid$(Text, Char + 1)
                            SelStart = SelStart - 1
                            Beep
                        Else
                            GotDecimalPt = True
                            Char = Char + 1
                        End If
                    Case Is < "0", Is > "9"
                        Text = Left$(Text, Char - 1) & Mid$(Text, Char + 1)
                        SelStart = SelStart - 1
                        Beep
                    Case Else
                        Char = Char + 1
                End Select
            Loop
            .Text = Text
            .SelStart = SelStart
        End If
    End With
End Sub