首页 > 解决方案 > 如何选择突出显示的列表框项目以添加到文本框

问题描述

我的代码有一个列表框,其中填充了常见的小文本字符串,用户可以单击以添加到 texbox,而不是手动输入它们。除了无法再次单击先前选择的项目以添加到文本框外,它在所有方面都有效。

我已经尝试设置 listbox.selected = -1 和 listbox1.value ="" ,当我这样做时,文本被添加了两次并且没有被取消选择。在某一时刻,我能够制作一个只执行 listbox1.value = "" 的按钮并且它有效,但是当我在我的代码之后添加它时它失败并执行双文本的事情。

Private Sub ListBox1_Click()
For i = 0 To ListBox1.ListCount - 1
If ListBox1.selected(i) Then
selecteditemtext = ListBox1.List(i)
End If
Next i
TextBox2.Text = TextBox2.Text & selecteditemtext & ", "

我需要它用于选定的列表框项目在被单击后变为未选中状态,因此可以在需要时再次单击它。

当我逐行运行此代码时,它可以工作。但所有这些都将文本添加了两次。

Private Sub ListBox1_Click()
For i = 0 To ListBox1.ListCount - 1
If ListBox1.selected(i) Then
selecteditemtext = ListBox1.List(i)
End If
Next i
TextBox2.Text = TextBox2.Text & selecteditemtext & ", " 
call listdeselect
end sub

sub listdeselect()
sheet1.listbox1.value = ""
end sub

标签: excelvbalistboxselected

解决方案


我相信我有你的解决方案:)

在 MouseUp 事件中控制取消选择,如下所示:

Private Sub ListBox1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    ListBox1.ListIndex = -1
End Sub

只要您不中断 MouseUp 事件(例如使用 MsgBox),这似乎工作正常。

我使用的示例代码如下:

Private Sub UserForm_Activate()
    ListBox1.AddItem "asd"
    ListBox1.AddItem "sad"
    ListBox1.AddItem "dsa"
    ListBox1.AddItem "das"
End Sub

Private Sub ListBox1_Click()
    Sheets(1).Cells(1).Value = ListBox1.List(ListBox1.ListIndex)
    'MsgBox "hi"   'notice this disrupts the MouseUp event...
End Sub

Private Sub ListBox1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    ListBox1.ListIndex = -1
End Sub

我希望这能解决你的问题,干杯


推荐阅读