0

I was using the following code to select text inside a text box of a userform everytime I clicked on it, however I have almost 40 text boxes and I would like to know if there's a way to write a single code for all of them instead of copying and pasting this same piece of code 40 times.

Private Sub textbox1_MouseDown(ByVal Button As Integer, _ 
ByVal Shift As Integer,ByVal X As Single, ByVal y As Single)

With Me.textbox1
    .SelStart = 0
    .SelLength = Len(.Text)
End With

End Sub
pmv
  • 13
  • 1
  • 3
  • Create a user class that encapsulates the text box. Then your main code will simply create an object (your new class) that creates the text box and will select your text as needed. – PeterT Jun 07 '16 at 20:48
  • Thanks Peter. I'm pretty new to vba/userforms and I don't understand how to create a user class – pmv Jun 07 '16 at 21:20
  • This post could help you: [assign-code-to-a-button-created-dynamically](http://stackoverflow.com/questions/10224511/assign-code-to-a-button-created-dynamically) – Kellsens Jun 10 '16 at 16:21

1 Answers1

0

There are ways to write a single instance that will run for them all.

You will need to add a line of code for the MouseDown event for each textbox that will call the single instance of the code.

For example: -

Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
SelectText
End Sub

Then create a procedure that works on the ActiveControl: -

Private Sub SelectText()
With ActiveControl
    .SelStart = 0
    .SelLength = Len(.Text)
End With
End Sub
Gary Evans
  • 1,850
  • 4
  • 15
  • 30
  • Thank you Gary, but what if the textboxes do not have a common name? I cannot change them as this point since they are called the same as my columns in a spreadsheet and I'm using this logic for another part of the code. – pmv Jun 07 '16 at 21:19
  • @pmv I've changed the answer, as it is only your text boxes that will call the common procedure (`SelectText` in the example) then we do not need to worry about any form of checking the control type. – Gary Evans Jun 07 '16 at 21:56