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

前端 未结 10 2237
灰色年华
灰色年华 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:43

    Can't be more simple than this I guess...

    Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
    ByVal X As Single, ByVal Y As Single)
        With TextBox1
            .SelStart = 0
            .SelLength = Len(.Text)
        End With
    End Sub
    

    Whether you click on the textbox or you tab into it, it will do what you want. To deselect the text, use the arrow keys.

    Explanation

    If you debug the code you will see that even though you have said .SetFocus, the focus is not on the Textbox. .SetFocus doesn't work in TextBox1_Enter() and you need to have focus for the rest of the code to work. And hence my alternative...

    Alternative

    You may also like this version :) This overcomes the limitation of using the mouse in the TextBox

    Dim boolEnter As Boolean
    
    Private Sub TextBox1_Enter()
        boolEnter = True
    End Sub
    
    Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
    ByVal X As Single, ByVal Y As Single)
        If boolEnter = True Then
            With TextBox1
                .SelStart = 0
                .SelLength = Len(.Text)
            End With
            boolEnter = False
        End If
    End Sub
    

提交回复
热议问题