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

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

    I couldn't manage to select/highlight text in the Enter event as the the mousedown and mouseup events coming after are somewhat resetting the selection.

    I think the most proper way of achieving what you want is this :

    ' if you want to allow highlight more then once, reset the  variable LastEntered prior to call SelectTboxText:
    '       LastEntered = ""
    '       SelectTboxText TextBox2
    
    
    Dim LastEntered As String
    
    
    ' Button to select Textbox1
    Private Sub CommandButton1_Click()
        SelectTboxText TextBox1
    End Sub
    
    ' Button to select Textbox2
    Private Sub CommandButton2_Click()
        SelectTboxText TextBox2
    End Sub
    
    Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
        SelectTboxText TextBox1
    End Sub
    
    
    Private Sub TextBox2_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
         SelectTboxText TextBox2
    End Sub
    
    
    Public Sub SelectTboxText(ByRef tBox As MSForms.TextBox)
    
        If LastEntered <> tBox.Name Then
    
            LastEntered = tBox.Name
    
            With tBox
                .SetFocus
                .SelStart = 0
                .SelLength = Len(.Text)
            End With
    
        End If
    
    End Sub
    

    So each time you want to activate one of the textbox programmatically, you should call the sub SelectTboxText, which is not really annoying IMO. I made 2 buttons for this as an example.

提交回复
热议问题