问题
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