组合框更改事件每次在 excel VBA 中触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9870647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
combobox change event is firing every time in excel VBA
提问by Akki J
I am getting an XML that contains data to be bound to combobox. While binding this data each time when an item is added to the combobox, its change event is fired. I want to fire change event only after data is bound and user selects any item.
我得到一个 XML,其中包含要绑定到组合框的数据。每次将项目添加到组合框时绑定此数据时,都会触发其更改事件。我只想在绑定数据并且用户选择任何项目后才触发更改事件。
Any help, code that can solve this problem?
任何帮助,可以解决这个问题的代码?
回答by Alex K.
Use a flag to indicate whether or not you want to handle the event;
使用标志来指示是否要处理该事件;
private mblIsUpdating as boolean
...
sub addDataFromXml
mblIsUpdating = true
combo.additem ...
mblIsUpdating = false
end sub
sub combo_change
if (mblIsUpdating) then exit function
//handle change
end sub
回答by mischab1
In my experience, the combobox change event only fires when changing the combobox list of items if the combobox's value is not null. If this problem is happening when you first initialize the combobox, don't assign a default value until after you fill the combobox.
根据我的经验,如果组合框的值不为空,组合框更改事件只会在更改项目的组合框列表时触发。如果第一次初始化组合框时发生此问题,请在填充组合框之前不要分配默认值。
If you need to change the combobox list at other times, like Alex K says, create a boolean flag to indicate if you want to ignore the change event.
如果您需要在其他时间更改组合框列表,如 Alex K 所说,请创建一个布尔标志以指示您是否要忽略更改事件。
I'm not clear from your question if the change event is firing once as you populate the combobox or once for each .AddItem
. If it is the latter issue, then you can cut down on the number of change events by creating an array of values for your combobox and assigning it to the combobox's .List
.
我不清楚您的问题是在填充组合框时更改事件是触发一次还是为每个.AddItem
. 如果是后一个问题,那么您可以通过为组合框创建一组值并将其分配给组合框的.List
.
Here is an example with a 2-d array that is populating the combobox with the names and paths of all the open workbooks. (A 1-d array also works.)
这是一个二维数组示例,该数组使用所有打开的工作簿的名称和路径填充组合框。(一维数组也适用。)
Private Sub InitializeComboBox()
Dim aList() As String
Dim i As Integer, iMax As Integer
' build combobox list with zero-based array
iMax = Application.Workbooks.Count - 1
ReDim aList(iMax, 2)
For i = 0 To iMax
With Application.Workbooks(i + 1)
aList(i, 0) = i
aList(i, 1) = .Name
aList(i, 2) = .Path
End With
Next i
With Me.ComboBox1
.ColumnCount = 3
.ColumnWidths = "0 pt;80 pt;220 pt"
.ListWidth = "300 pt"
.List = aList
End With
End Sub