vba listbox事件触发两次

时间:2016-04-14 12:46:54

标签: excel vba events listbox

我试图在excel用户表单中使用它。在列表框中选择值时,会更改其更改事件两次。即使在放置旗帜后也无法绕过它。不确定为什么更改事件被调用两次。在谷歌搜索它之后,就像控件获得焦点一样,调用change事件。以下是代码。

Public eventsOFF As Boolean
Public ctr As Integer

Private Sub ListBox1_Change()
Dim tmp As String, sel As Variant, s As Variant

If eventsOFF Then Exit Sub

eventsOFF = True
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then tmp = tmp & ListBox1.List(i) & ","
Next

ListBox1.Clear
sel = Split(tmp, ",")

ListBox1.AddItem "Entry 1"
ListBox1.AddItem "Entry 2"
ListBox1.AddItem "Entry 3"
ListBox1.AddItem "Entry 4"
ListBox1.AddItem "Entry 5"

For i = 0 To ListBox1.ListCount - 1
For Each s In sel
If s = ListBox1.List(i) Then ListBox1.Selected(i) = True
Next
Next
eventsOFF = False
ctr = ctr + 1
Debug.Print ctr
End Sub

Private Sub UserForm_Initialize()
ListBox1.AddItem "Entry 1"
ListBox1.AddItem "Entry 2"
ListBox1.AddItem "Entry 3"
ListBox1.AddItem "Entry 4"
ListBox1.AddItem "Entry 5"
End Sub

1 个答案:

答案 0 :(得分:1)

在ListBox1_MouseMove事件下插入以下行将解决您的问题

ListBox1.SetFocus