2017-06-12 52 views
0

我已经获得了由标签,复选框和文本框组成的动态生成的用户窗体。点击时是否可以选择文本框的内容? 这是方法我使用创建文本框:单击时突出显示文本框内容

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特定的文本框的子。但正如我所说,代码从头开始生成一切。 所以如果有一个财产,或其他方式来完成它,我会gratefull。

回答

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 
在用户窗体代码

然后类模块

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 
+0

非常感谢,这个奇妙的工作,并与只进行了少量的代码适应。有没有机会你可以在下午向我解释你的代码?它的工作原理,但我不知道如何:) –

相关问题