请教VB高手:VB文本框禁止输入数字、减号、小数点意外的字符。

2025-04-08 04:00:39
推荐回答(1个)
回答1:

Dim OldText As String

Private Sub Form_Load()
Text1.Text = ""
End Sub

Private Sub Text1_Change() '屏蔽粘贴非数字
If IsNumeric(Text1.Text) And Right(Text1.Text, 1) <> "-" Or Text1.Text = "" Or Text1.Text = "-" Then
    OldText = Text1.Text
Else
    Text1.Text = OldText
    Text1.SelStart = Len(Text1.Text)
End If
If IsNumeric(Text1.Text) Then
    Command1.Enabled = True
Else
    Command1.Enabled = False
End If
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii >= 48 And KeyAscii <= 57 Or KeyAscii = 46 Or KeyAscii = 45 And Text1.SelStart = 0 Then
    If Not IsNumeric(Text1.Text & Chr(KeyAscii)) And Text1.Text <> "" Then
        KeyAscii = 0
    End If
End If
End Sub