在form1中,我有10个文本框,想把文本框限制为只能输入数字,输入其他的将会出错。现运用Validate事件,用控件数组如何解决这个问题。单个文本框Validate事件格式如下。
Private Sub Text1_Validate(Keepfocus As Boolean)
If Not IsNumeric(Text1.Text) Or Val(Left(Text1.Text, 1)) = 0 Then
Keepfocus = True
MsgBox "请输入有效数字.", vbCritical, "Error"
End If
End Sub
Private Sub Text1_Validate(Keepfocus As Boolean)
If Not IsNumeric(Text1.Text) Or Val(Left(Text1.Text, 1)) = 0 Then
Keepfocus = True
MsgBox "请输入有效数字.", vbCritical, "Error"
End If
End Sub
shuzi KeyAscii
End Sub
Public Sub shuzi(KeyAscii As Integer) '只允许输入数字 If KeyAscii = 8 Then 'backSpace=8 ,下箭头=40
KeyAscii = 8
ElseIf KeyAscii = 13 Then ' The ENTER key.
SendKeys "{tab}" ' Set the focus to the next control.
KeyAscii = 0 ' Ignore this key.
ElseIf KeyAscii < 48 Or KeyAscii > 57 Then
KeyAscii = 0
End IfEnd Sub
Private Sub Text1_KeyPress(Index As Integer, KeyAscii As Integer)
shuzi KeyAsciiEnd Sub
创建text的时候用相同名字
index属性从0到N
这样一个sub解决全部问题
新建一个工程,放置一个txtbox,再点右键复制粘贴,自动粘贴为控件数组,然后将下面代码放进去
Option Explicit
Private Sub Text1_KeyPress(Index As Integer, KeyAscii As Integer)
shuzi KeyAscii
End SubPublic Sub shuzi(KeyAscii As Integer) '只允许输入数字 If KeyAscii = 8 Then 'backSpace=8 ,下箭头=40
KeyAscii = 8
ElseIf KeyAscii = 13 Then ' The ENTER key.
SendKeys "{tab}" ' Set the focus to the next control.
KeyAscii = 0 ' Ignore this key.
ElseIf KeyAscii < 48 Or KeyAscii > 57 Then
KeyAscii = 0
End IfEnd Sub
从你代码上看,你控件不是数组的,数组的应该是
Private Sub Text1_Validate(Index As Integer, Cancel As Boolean)
'文本匡输入限制 只能输入数字 0-9Option Explicit '强制宣告定义变量
Dim aa$ '定义变量
Private Sub Form_Load()
'将窗体居中显示 (屏幕宽度减去窗体的宽度)除以2 , (屏幕高度减去窗体的高度)除以2
Me.Move (Screen.Width - Me.Width) \ 2, (Screen.Height - Me.Height) \ 2
aa = "0123456789" '列出合法的字符,如还需要其它的字符,自己可以追加
End SubPrivate Sub Text1_KeyPress(Index As Integer, KeyAscii As Integer)
If KeyAscii <> 13 And InStr(aa, Chr(KeyAscii)) = 0 Then
MsgBox "请输入数字"
KeyAscii = 0
End If
End Sub