注册 登录
编程论坛 新人交流区

为什么我用退格退了两个数字????

初学vb 发布于 2007-10-02 16:36, 409 次点击

编程目的:在一个文本框内只能输入数字,输入错了可以用"{BackSpace}"删除。文本框的属性没有改动,但运行时按一次退格键却删了两个数字,办什么呢?????

请高手帮忙看看,附代码如下:

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

Private Sub Text1_KeyPress(KeyAscii As Integer)
If (KeyAscii > 47 And KeyAscii < 59) Or KeyAscii = 46 Then
If (Len(Text1.Text) < 1 And KeyAscii = 48) Then

KeyAscii = 0
Text1.Text = ""
End If
ElseIf (Len(Text1.Text) > 0 And KeyAscii = 8) Then
Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1) '用'SendKeys"{BackSpace}"也是一样
Text1.SelStart = Len(Text1.Text)
Else
MsgBox "请输入数字。", 0, "错误" 'vbDefaultButton1 'If Len(Text1.Text) > 0 Then Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)
' Text1.SelStart = Len(Text1.Text)
KeyAscii = 0
Text1.SelStart = Len(Text1.Text)
End If

End Sub

5 回复
#2
SkyAngel2007-10-02 16:39
ElseIf (Len(Text1.Text) > 0 And KeyAscii = 8) Then
Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1) '用'SendKeys"{BackSpace}"也是一样
Text1.SelStart = Len(Text1.Text)
Else

ElseIf (Len(Text1.Text) > 0 And KeyAscii = 8) Then
Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1) '用'SendKeys"{BackSpace}"也是一样
Text1.SelStart = Len(Text1.Text)
KeyAscii = 0
Else
#3
初学vb2007-10-02 16:43

谢谢SkyAngel啊,问题解决了。但是为什么会这样呢??

#4
SkyAngel2007-10-02 16:44
ElseIf (Len(Text1.Text) > 0 And KeyAscii = 8) Then
Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1) '用'SendKeys"{BackSpace}"也是一样
Text1.SelStart = Len(Text1.Text)
Else
改成
ElseIf (Len(Text1.Text) > 0 And KeyAscii = 8) Then
Else
也是一样的效果的
#5
初学vb2007-10-02 16:49

我想通了,因为按"{BackSpace}"时KeyAscii = "{BackSpace}"运行一次 Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)时,删一个字符。 结束时KeyAscii = "{BackSpace}"的值没变,所以还会执行"{BackSpace}",所以删两个数字。
是这个原因吧??

[此贴子已经被作者于2007-10-2 16:52:09编辑过]

#6
SkyAngel2007-10-02 17:02

smart guy

1