简体   繁体   中英

Iterate through a series of textboxes

I have about 13 textboxes in a MS-Word document using Active X textbox controls. I found this code that seems to work great in my test with a single textbox.

How can I cycle through all 13 textboxes by name instead of adding this code to all 13 textboxes.

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii > Asc("9") Or KeyAscii < Asc("0") Then
    If KeyAscii = Asc("-") Then
        If InStr(1, Me.TextBox1.Text, "-") > 0 Or _
           Me.TextBox1.SelStart > 0 Then KeyAscii = 0
    ElseIf KeyAscii = Asc(".") Then
        If InStr(1, Me.TextBox1.Text, ".") > 0 Then KeyAscii = 0
    Else
        KeyAscii = 0
    End If
End If
End Sub

You could do something like this:

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    HandleKeyPress Me.TextBox1, KeyAscii
End Sub

Private Sub TextBox2_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    HandleKeyPress Me.TextBox2, KeyAscii
End Sub



Private Sub HandleKeyPress(txtBox As Object, ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii > Asc("9") Or KeyAscii < Asc("0") Then
    If KeyAscii = Asc("-") Then
        If InStr(1, txtBox.Text, "-") > 0 Or _
          txtBox.SelStart > 0 Then KeyAscii = 0
    ElseIf KeyAscii = Asc(".") Then
        If InStr(1, txtBox.Text, ".") > 0 Then KeyAscii = 0
    Else
        KeyAscii = 0
    End If
End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM