通过在VBA用户窗体中双击,将列表框中的条目添加到最近的文本框中

我试图find一种方法让用户双击列表框中的一个条目,并将其粘贴到他们最近关注的文本框中。 所以,像列表框一样

With ListBox1 .AddItem "<PARENT> Customer's PARENT Company " .AddItem "<SALESEXEC> The sales executive responsible for the account" .AddItem "<FIRSTNAME> Customer's First Name" End With 

我希望能够将这些值过滤到一个文本框中,但是因为表单有多个文本框,所以我希望它是最后一个重点。 我正在考虑做下面的事情。 问题是我似乎无法得到GotFocus事件做任何事情。 它可以和Enter事件一起工作,但是只能使用一次。

 Public hasFoc As String Private Sub TextBox4_GotFocus() Debug.Print ("TextBox4 Clicked") hasFoc = "TextBox4" End Sub Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean) 'Get index of clicked element, and paste the "<>" 'value into the most recently used textbox End Sub 

编辑:我以前在VBA中没有处理过类,但是我的类模块看起来像这样:

 Option Explicit Public WithEvents txtBox As MSForms.TextBox '/ To Mimic Enter event . Private Sub txtBox_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) '/ Assign to global variable Set g_ActiveTextBox = txtBox End Sub '/ To Mimic Enter event . Private Sub txtBox_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) '/ Assign to global variable Set g_ActiveTextBox = txtBox End Sub 

您可以创build自定义事件处理程序类,通过捕获MouseDown和KeyDown事件来模拟Enter事件。 UserForm加载时,将所有文本框挂接到自定义事件。 每当用户访问TextBox时,将其存储在全局variables中(在标准模块中)。 在列表框DblClick上,只需将选定的项目文本设置为文本框。 简单!!! 🙂

请参阅下面的完整VBA代码:

VBA类(EventH)用于自定义事件处理。

 Option Explicit Public WithEvents txtBox As MSForms.TextBox '/ To Mimic Enter event . Private Sub txtBox_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) '/ Assign to global variable Set g_ActiveTextBox = txtBox End Sub '/ To Mimic Enter event . Private Sub txtBox_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) '/ Assign to global variable Set g_ActiveTextBox = txtBox End Sub 

VBA用户窗体,带有文本框和列表框

 Option Explicit Dim oCol As New Collection '/ Holds the custom events and keeps them alive Private Sub UserForm_Initialize() '/ Start EventHandler hooking. Call addEventhandlers End Sub Sub addEventhandlers() '/ Adds custom event handler to all TextBoxes of this UserForm Dim oEventH As EventH Dim ctrl As Control For Each ctrl In Me.Controls If TypeName(ctrl) = "TextBox" Then Set oEventH = New EventH Set oEventH.txtBox = ctrl oCol.Add oEventH End If Next End Sub Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean) '/ Copy Text from ListBox to Last active TextBox Dim i As Long If Not g_ActiveTextBox Is Nothing Then For i = 0 To Me.ListBox1.ListCount - 1 If Me.ListBox1.Selected(i) Then g_ActiveTextBox = Me.ListBox1.List(i) End If Next i End If End Sub 

一个标准模块来声明全局variables。

选项显式

 Global g_ActiveTextBox As MSForms.TextBox '/ Global variable to hold the last active textbox '/ Don't act smart and move it to UserForm as public. '/ That will fail.