VB的Text1_Change()事件中text只能是字母和数字
Private Sub Text1_Change()
'这里是代码( 不是text1_keypress事件,因为为了防止粘贴)
End Sub
真的很感谢∮酷帅男孩♂认真负责的回答,已经达到了效果,谢谢你!但是我觉得楼下的没有留名的朋友的代码效果更简洁明了,特别是解决了一旦输入数字和字母以外的字符时焦点会落到text的右边,就是"Text1.SelStart = Len(Text1)"这句。 展开
帮你写了下,希望对你有帮助。
代码如下:
Private Sub Text1_Change()
Dim i As Integer, j As Integer
Dim s As String, str As String
s = ""
For i = 1 To Len(Text1.Text)
s = Mid(Text1.Text, i, 1)
If Not (Asc(s) >= Asc("0") And Asc(s) <= Asc("9") Or Asc(s) >= Asc("a") And Asc(s) <= Asc("z") Or Asc(s) >= Asc("A") And Asc(s) <= Asc("Z")) Then
MsgBox "只能输入数字或字母!", vbExclamation, "提示信息"
str = ""
For j = 1 To Len(Text1.Text)
str = Mid(Text1.Text, j, 1)
If Asc(str) >= Asc("0") And Asc(str) <= Asc("9") Or Asc(str) >= Asc("a") And Asc(str) <= Asc("z") Or Asc(str) >= Asc("A") And Asc(str) <= Asc("Z") Then
txt = txt & str
End If
Next j
Text1.Text = txt
Exit For
End If
Next i
End Sub
界面上就一个TEXT控件,名称是Text1.
PS:注意某些换行是百度自动换行的,把语句并成一行后就可以运行了!
图为测试运行后结果,当最后输入了“!”后弹出了提示对话框。
2010-11-03
ss = Text1
For i = Len(ss) To 1 Step -1
s = Mid(ss, i, 1)
a = Asc(s)
If a < 48 Or (a > 57 And a < 65) Or (a > 90 And a < 97) Or a > 122 Then ss = Left(ss, i - 1) & Mid(ss, i + 1)
Next
Text1 = ss
Text1.SelStart = Len(Text1)
End Sub