highlighting textbox content upon click

微笑、不失礼 提交于 2020-06-18 14:12:30

问题


i've got dynamically generated userform consisting of labels, checkboxes and text boxes. is it possible to have a contents of a textbox selected when clicked? this is method i'm using to create textbox:

Set NewTextBox = MainFrame.Controls.Add("Forms.TextBox.1")
With NewTextBox
    .Name = "QtyTB" & row
    .Value = Cells(cellrow - 1 + row, 11)
    .Height = 18
    .Left = 210
    .Top = 18
    .Width = 36
    .Enabled = True
    .BackColor = RGB(255, 255, 0)
End With

if i was to create textbox manually i could write on_click sub for specific text box. but as i said, code generates everything from scratch. so if there is a property, or some other way to get it done, i would be gratefull.


回答1:


Yes, this can be done by creating a class module with event handling

The following code will need a bit of adaption as there isn't much code to go on in the question...

In a class module called TextBoxEventHandler

Private WithEvents FormTextBox As MSForms.TextBox

Public Property Set TextBox(ByVal oTextBox As MSForms.TextBox)
    Set FormTextBox = oTextBox
End Property

Private Sub FormTextBox_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    If Button = 1 Then
        With FormTextBox
            .SelStart = 0
            .SelLength = Len(.Text)
        End With
    End If
End Sub

Then in the UserForm code

Private CollectionOfEventHandlers As Collection

Private Sub UserForm_Initialize()
    Dim i As Long
    Dim NewTextBox As MSForms.TextBox

    For i = 0 To 4
        Set NewTextBox = Me.Controls.Add("Forms.TextBox.1")
        With NewTextBox
            .Name = "QtyTB" & i ' Row
            .Value = "Text " & i ' Cells(cellrow - 1 + Row, 11)
            .Height = 18
            .Left = 21
            .Top = 18 + i * 25
            .Width = 36
            .Enabled = True
            .BackColor = RGB(255, 255, 0)
        End With
    Next i
    Call InitialiseHandlers
End Sub

Private Function InitialiseHandlers()
    Set CollectionOfEventHandlers = New Collection
    Dim FormControl As Control
    For Each FormControl In Me.Controls
        If TypeName(FormControl) = "TextBox" Then
            Dim EventHandler As TextboxEventHandler
            Set EventHandler = New TextboxEventHandler
            Set EventHandler.TextBox = FormControl
            CollectionOfEventHandlers.Add EventHandler
        End If
    Next FormControl
End Function


来源:https://stackoverflow.com/questions/44509112/highlighting-textbox-content-upon-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!