在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

解决方案 »

  1.   

    这样就可以只输入数字了,你试下就知道了Private Sub Text1_KeyPress(KeyAscii As Integer)
    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
      

  2.   

    这样就可以了,你新建个工程试下就知道了
    Private Sub Text1_KeyPress(Index As Integer, KeyAscii As Integer)
    shuzi KeyAsciiEnd Sub
      

  3.   

    饿和上面说的一样,,,
    创建text的时候用相同名字 
    index属性从0到N
    这样一个sub解决全部问题
      

  4.   

    不可能啊
    新建一个工程,放置一个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
      

  5.   

    Private Sub Text1_Validate(Keepfocus As Boolean)
    从你代码上看,你控件不是数组的,数组的应该是
    Private Sub Text1_Validate(Index As Integer, Cancel As Boolean)
      

  6.   

    楼主 请先在属性窗里查看你的 Text1的Index是否有数字 0? '摘录自 CBM666编程示例教材 文本文件篇
    '文本匡输入限制 只能输入数字 0-9
    Option 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
      

  7.   

    感谢大家。特别感谢fly1229.