Private Sub Text1_KeyPress(KeyAscii As Integer) Dim i, L As Integer If Not (KeyAscii > 47 And KeyAscii < 58 Or KeyAscii = 46) Then KeyAscii = 0 L = Len(Text1.Text) For i = 1 To L If Mid(Text1.Text, i, 1) = "." Then Exit For Next i If L - i >= 2 Then MsgBox "只能输入两位小数。": KeyAscii = 0 End Sub
都有问题,我想这样改改,会好一点 Private Sub Text1_KeyPress(KeyAscii As Integer) Dim i, L As Integer '应该可以回退,Keyascii=46 If Not (KeyAscii > 47 And KeyAscii < 58 Or KeyAscii = 46 Or KeyAscii = 8) Then KeyAscii = 0 End If L = Len(Text1.Text) For i = 1 To L If Mid(Text1.Text, i, 1) = "." Then Exit For '防止有多个小数点 If KeyAscii = 46 Then If InStr(Trim(Text1.Text), ".") <> 0 Then KeyAscii = 0 End If End If Next i '可以回退 If L - i >= 2 And KeyAscii <> 8 Then KeyAscii = 0 End If End Sub
注释错了 '应该可以回退,Keyascii=8
看来还是容易受人干扰,上面的算法,可能比较低效,另外还应排除小数点在最前面的情况,试试这个 Private Sub Text1_KeyPress(KeyAscii As Integer) Dim i, L As Integer '应该可以回退,Keyascii=46 If Not (KeyAscii > 47 And KeyAscii < 58 Or KeyAscii = 46 Or KeyAscii = 8) Then KeyAscii = 0 End If i = InStr(Trim(Text1.Text), ".") L = Len(Text1.Text) If KeyAscii = 46 Then 'L=0小数点在最前面,i<>0已经存在一个小数点 If L = 0 Or i <> 0 Then KeyAscii = 0 End If If i <> 0 Then If L - i >= 2 And KeyAscii <> 8 Then KeyAscii = 0 End If End If End Sub
Dim i, L As Integer
If Not (KeyAscii > 47 And KeyAscii < 58 Or KeyAscii = 46) Then KeyAscii = 0
L = Len(Text1.Text)
For i = 1 To L
If Mid(Text1.Text, i, 1) = "." Then Exit For
Next i
If L - i >= 2 Then MsgBox "只能输入两位小数。": KeyAscii = 0
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim i, L As Integer
'应该可以回退,Keyascii=46
If Not (KeyAscii > 47 And KeyAscii < 58 Or KeyAscii = 46 Or KeyAscii = 8) Then
KeyAscii = 0
End If
L = Len(Text1.Text)
For i = 1 To L
If Mid(Text1.Text, i, 1) = "." Then Exit For
'防止有多个小数点
If KeyAscii = 46 Then
If InStr(Trim(Text1.Text), ".") <> 0 Then
KeyAscii = 0
End If
End If
Next i
'可以回退
If L - i >= 2 And KeyAscii <> 8 Then
KeyAscii = 0
End If
End Sub
'应该可以回退,Keyascii=8
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim i, L As Integer
'应该可以回退,Keyascii=46
If Not (KeyAscii > 47 And KeyAscii < 58 Or KeyAscii = 46 Or KeyAscii = 8) Then
KeyAscii = 0
End If
i = InStr(Trim(Text1.Text), ".")
L = Len(Text1.Text)
If KeyAscii = 46 Then
'L=0小数点在最前面,i<>0已经存在一个小数点
If L = 0 Or i <> 0 Then KeyAscii = 0
End If
If i <> 0 Then
If L - i >= 2 And KeyAscii <> 8 Then
KeyAscii = 0
End If
End If
End Sub
谢谢`~~