回 帖 发 新 帖 刷新版面

主题:又有新问题...

我想对文本框设置只能输入数字,就写了下面这段代码:
Private Sub Text1_KeyPress(KeyAscii As Integer)
  If Chr(KeyAscii) < "0" Or Chr(KeyAscii) > "9" Then
  KeyAscii = 0
  End If
End Sub
可完了发现如果写错了连退格键都不能用了,小数点什么的都不能用,请问如果我只想限制不能输入字母而键盘其他的键还可以用的话应该怎么写这段代码?[em10]

回复列表 (共13个回复)

沙发

还有,如果我是想让text1到text7都是这样的话只能一个一个的写这段代码吗?有没有办法能批量设置?

板凳

又想起一个,如果是只想键盘的一部分可以用,比如只能写入数字,小数点,退格键这三个其他通通不能用的话该怎么办呢...

3 楼

[quote]如果我是想让text1到text7都是这样的话只能一个一个的写这段代码吗?有没有办法能批量设置?[/quote]
自己做个控件来重用。

[quote]只能写入数字,小数点,退格键这三个其他通通不能用的话该怎么办呢...[/quote]
Private Sub Text1_KeyPress(KeyAscii As Integer)
'只能写入数字,小数点,退格键这三个其他通通不能用的话该怎么办呢...
'If Not ((KeyAscii = 8) Or (KeyAscii = Asc(".")) Or (KeyAscii >= Asc("0") And KeyAscii <= Asc("9"))) Then
If (KeyAscii <> 8) And (KeyAscii <> Asc(".")) And (KeyAscii < Asc("0") Or KeyAscii > Asc("9")) Then
     KeyAscii = 0
End If
End Sub

4 楼

谢谢前辈!^-^

5 楼

[quote]还有,如果我是想让text1到text7都是这样的话只能一个一个的写这段代码吗?有没有办法能批量设置?[/quote]

可以用控件数组,7个TextBox分别为Text1(0)-Text1(6)
然后只写一次代码就够了

6 楼

Private Sub Form_KeyPress(KeyAscii As Integer)
   If TypeName(Me.ActiveControl) = "TextBox" Then
    If Not ("0123456789." & chr(8) Like ("*" & Chr(KeyAscii) & "*")) Then KeyAscii = 0
   End If
End Sub

Private Sub Form_Load()
 Me.KeyPreview = True
End Sub

7 楼

[quote][quote]还有,如果我是想让text1到text7都是这样的话只能一个一个的写这段代码吗?有没有办法能批量设置?[/quote]

可以用控件数组,7个TextBox分别为Text1(0)-Text1(6)
然后只写一次代码就够了[/quote]
是吗?!我试试!谢谢!

8 楼

[quote]Private Sub Form_KeyPress(KeyAscii As Integer)
   If TypeName(Me.ActiveControl) = "TextBox" Then
    If Not ("0123456789." & chr(8) Like ("*" & Chr(KeyAscii) & "*")) Then KeyAscii = 0
   End If
End Sub

Private Sub Form_Load()
 Me.KeyPreview = True
End Sub[/quote]
这个对我来说太难,我们才学没多久,有些函数还看不懂...谢谢!

9 楼

Option Explicit

Private Const GWL_STYLE = (-16)
Private Const ES_NUMBER = &H2000
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long

Private Sub Form_Load()
    
    Dim ctl As Control, ls As Long
    '枚举窗体上所有控件
    For Each ctl In Me.Controls
        '判断是否为TextBox控件
        If TypeName(ctl) = "TextBox" Then
            '获取TextBox控件的风格,并与ES_NUMBER进行位或运算,再设置新风格
            ls = GetWindowLong(ctl.hwnd, GWL_STYLE)
            Call SetWindowLong(ctl.hwnd, GWL_STYLE, ls Or ES_NUMBER)
        End If
    Next
    
End Sub

10 楼

这个我就更看不懂了.....-_-".....

我来回复

您尚未登录,请登录后再回复。点此登录或注册