vba listbox事件触发两次 [英] vba listbox event fires twice

查看:122
本文介绍了vba listbox事件触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使其在excel用户表单中起作用.在列表框中选择一个值时,其更改事件被调用两次.即使在放置标志后也无法绕开它.不知道为什么更改事件被调用两次.进行谷歌搜索后,就像控件获得焦点时一样,将调用change事件.下面是代码.

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

推荐答案

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

Under ListBox1_MouseMove event insert the following line will solve your problem

ListBox1.SetFocus

ListBox1.SetFocus

这篇关于vba listbox事件触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆