How to select the contents of a textbox once it is activated?

前端 未结 10 2242
灰色年华
灰色年华 2020-12-06 05:16

I have this simple Userform, where I only have TextBox1 and TextBox2. I enter some text in both of them. Assume the focus is on (the cursor is in)

10条回答
  •  一个人的身影
    2020-12-06 05:49

    Pff, took me a while. Actually, your code works, but it highlights the text BEFORE the click event happens. So you clicking in the box instantly overrides the selection created by the code. I have used a delayed selection, and it works, though it is a bit disgusting...

    The code for the textboxes:

    Private Sub TextBox1_Enter()
      Application.OnTime Now + TimeValue("00:00:01"), "module1.SelectText1"
    End Sub
    
    Private Sub TextBox2_Enter()
      Application.OnTime Now, "module1.SelectText2"
    End Sub
    

    Note that it works even withouth the {+ TimeValue("00:00:01")} part, but it might theoretically stop it from working at times. Hmm, on a second thought, just leave it out. I doubt it would ever cause a problem.

    Now the code in module1:

    Sub SelectText1()
      UserForm1.TextBox1.SelStart = 0
      UserForm1.TextBox1.SelLength = Len(UserForm1.TextBox1.Text)
    End Sub
    
    Sub SelectText2()
      UserForm1.TextBox2.SelStart = 0
      UserForm1.TextBox2.SelLength = Len(UserForm1.TextBox2.Text)
    End Sub
    

    Hope this works for you too. Ineresting problem. :) Cheers!

提交回复
热议问题