我有动态生成的用户表单,包括标签,复选框和文本框。是否可以在单击时选择文本框的内容? 这是我用来创建文本框的方法:
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
如果我要手动创建文本框,我可以为特定文本框写on_click sub。但正如我所说,代码从头开始生成所有内容。 所以,如果有财产或其他方式来完成,我将感激不尽。
答案 0 :(得分:0)
是的,这可以通过创建一个带有事件处理的类模块来完成
以下代码需要进行一些调整,因为问题中没有太多代码可以继续......
在名为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
然后在UserForm代码中
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