Reputation: 1
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
Upvotes: 0
Views: 44
Reputation: 166316
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
Upvotes: 1