vba listbox event fires twice

萝らか妹 提交于 2021-02-11 11:49:07

问题


I am trying to get this to work in excel userforms. When selecting a value in the listbox its change event is called twice. Unable to get around it even after putting a flag in place. Not sure why the change event is called twice. After googling it seams like when the control gets focus the change event is called. Below is the code.

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:


Under ListBox1_MouseMove event insert the following line will solve your problem

ListBox1.SetFocus



来源:https://stackoverflow.com/questions/36623581/vba-listbox-event-fires-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!