excel - 如何选择突出显示的列表框项目以添加到文本框
问题描述
我的代码有一个列表框,其中填充了常见的小文本字符串,用户可以单击以添加到 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
解决方案
我相信我有你的解决方案:)
在 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
我希望这能解决你的问题,干杯
推荐阅读
- javascript - 如何在javascript上提取二维数组
- ios - 当最小部署目标设置为 iOS 12.2 时,如何有条件地使用组合 @Published?
- c# - 基于实体字段和拥有值对象字段的 C# EF 索引
- c# - 如何将“多个间隔”添加到 .Net 图表?
- winforms - 相当于 Windows 窗体 (.net) 中的“Zone répétée”
- javascript - 样式不适用于我在 TypeScript 中创建的 React 库
- java - Spring 端点为较大的 http 请求接收截断的正文
- python - 对训练和测试数据帧使用相同的标签编码器
- python - 我怎样才能将这些注释添加到这个二次贝塞尔曲线?
- visual-studio - 无法编译 VTK 解决方案的安装项目