文本框本来就接受文本的,你要它不接受字符可能不行。但如果你一定要这样做,可在文本框的Chang事件中写上以下代码:
Private Sub Text1_Change()
On Error Resume Next
If Asc(Text1.Text) < 48 Or Asc(Text1.Text) > 57 Then Text1.Text = ""
End Sub
不要任何提示通用的方法是用钩子,相当繁琐,网上有相关代码。这里介绍一种我刚想到的一种方法,使用延时完成,一般可以欺骗常规用户(鼠标右键按长点时间,仍然会弹出右键菜单,但粘贴选项变灰;了)
Private Sub Text1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim t As Single
If Button = 2 Then
Clipboard.Clear '清除粘贴板内容,万一弹出也没有什么可以粘贴
Text1.Enabled = False
t = Timer * 1000
While Timer * 1000 - t < 300 '通过实验,0.3秒是一个合适的时间,不容易弹出右键菜单
DoEvents
Wend
Text1.Enabled = True
Text1.SetFocus
End If
End Sub
不要任何提示通用的方法是用钩子,相当繁琐,网上有相关代码。这里介绍一种我刚想到的一种方法,使用延时完成,一般可以欺骗常规用户(鼠标右键按长点时间,仍然会弹出右键菜单,但粘贴选项变灰;了)
Private Sub Text1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim t As Single
If Button = 2 Then
Clipboard.Clear '清除粘贴板内容,万一弹出也没有什么可以粘贴
Text1.Enabled = False
t = Timer * 1000
While Timer * 1000 - t < 300 '通过实验,0.3秒是一个合适的时间,不容易弹出右键菜单
DoEvents
Wend
Text1.Enabled = True
Text1.SetFocus
End If
End Sub
Dim i As Long, o As Long 'i 是循环变量,o 是中间变量
Dim xs As Boolean '小数点存在
Dim s1 As String '原始数据
Dim s2 As String '新数据
Dim l As Long '光标位置
l = Text1.SelStart '取光标位置
s1 = Text1.Text '取原始数据
For i = 1 To Len(s1) '循环
o = Asc(Mid(s1, i, 1)) '取一位
If o = 46 Then '小数点
If xs Then '存在
o = 0 '取消
Else
xs = True '保存已存在小数点
End If
ElseIf o < 48 Or o > 57 Then '非数字
o = 0 '取消
End If
If o > 0 Then '非取消
s2 = s2 & Chr(o) '生成结果
End If
Next i
If s1 <> s2 Then '如果过滤后的数据有变化
Text1.Text = s2 '此处会造成再次触发本事件。
Text1.SelStart = l - 1 '恢复光标位置
End If