Public Function sffunLimitNumber(ByVal IntVal As Integer) As Integer '-------------------1------------------- '目 的:只允许在文本框内输入数字、退格、删除及回车键 '输 入:ByVal IntVal As Integer,任意的键值 '被传递值:无 '返 回 值:过滤后的键值 '输 出:无 '注 解: '用 法:在文本框的KeyPress事件中输入KeyAscii = sffunLimitNumber(KeyAscii)即可 '修 订 版: '-------------------1------------------- If (IntVal <> vbKeyDelete) _ And (IntVal <> vbKeyBack) _ And (IntVal <> 13) _ And (IntVal < 48 Or IntVal > 57) Then IntVal = 0 End If sffunLimitNumber = IntValEnd Function
if not isnumeric(text1.text) then msgbox "您输入的不是数字,请重新输入",vbyesno txt.gotfocue
api方法Public Function NumbersOnly(tBox As TextBox) Dim DefaultStyle As Long DefaultStyle = GetWindowLong(tBox.hWnd, GWL_STYLE) NumbersOnly = SetWindowLong(tBox.hWnd, GWL_STYLE, DefaultStyle Or ES_NUMBER) End Function
Option Explicit Dim decimaltag As BooleanPrivate Sub Form_Load() decimaltag = False End SubPrivate Sub Text1_Change() If InStr(1, Trim$(Text1.Text), ".") Then decimaltag = True End If End SubPrivate Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = 46 And decimaltag = False Then decimaltag = True '控制小数点只能输入一次。 ElseIf KeyAscii >= vbKey0 And KeyAscii <= vbKey9 Then Exit Sub ElseIf KeyAscii <= 31 Then Exit Sub '控制可接受退格键或删除键等。 Else KeyAscii = 0 End If End Sub
它与文本框(TEXT BOX)功能基本相似,但多了一个MASK属性,MASK属性常用的设定如下:
#—限定仅能输入数字0~9;
A— 限定输入为英文字符及数字;
?—限定仅能输入英文字符;
.—限定小数点位置;
:—限定时间分隔号;
/—限定日期分隔号
不需编写代码,只要在设计时将格式化文本框对象(MASKED EDIT)的MASK属性设计好所需格式即可。比如 #######.##可输入12.3或123456.78但不能输入字母或其他字符但你必须考虑你输入的数字的位数,例如,如果把mask属性设为###.##,那么就只可以输入123.45,而不能输入1234.56,所以,最好把位数设得足够多。这样,你不需要写一行程序,只需要设定masked edit控件的属性就可以达到你的目的了
'-------------------1-------------------
'目 的:只允许在文本框内输入数字、退格、删除及回车键
'输 入:ByVal IntVal As Integer,任意的键值
'被传递值:无
'返 回 值:过滤后的键值
'输 出:无
'注 解:
'用 法:在文本框的KeyPress事件中输入KeyAscii = sffunLimitNumber(KeyAscii)即可
'修 订 版:
'-------------------1-------------------
If (IntVal <> vbKeyDelete) _
And (IntVal <> vbKeyBack) _
And (IntVal <> 13) _
And (IntVal < 48 Or IntVal > 57) Then
IntVal = 0
End If
sffunLimitNumber = IntValEnd Function
msgbox "您输入的不是数字,请重新输入",vbyesno
txt.gotfocue
Dim DefaultStyle As Long
DefaultStyle = GetWindowLong(tBox.hWnd, GWL_STYLE)
NumbersOnly = SetWindowLong(tBox.hWnd, GWL_STYLE, DefaultStyle Or ES_NUMBER)
End Function
Dim decimaltag As BooleanPrivate Sub Form_Load()
decimaltag = False
End SubPrivate Sub Text1_Change()
If InStr(1, Trim$(Text1.Text), ".") Then
decimaltag = True
End If
End SubPrivate Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 46 And decimaltag = False Then
decimaltag = True '控制小数点只能输入一次。
ElseIf KeyAscii >= vbKey0 And KeyAscii <= vbKey9 Then
Exit Sub
ElseIf KeyAscii <= 31 Then
Exit Sub '控制可接受退格键或删除键等。
Else
KeyAscii = 0
End If
End Sub