为什么(Excel VBA)combobox更改事件每次触发它的一个属性被引用?

我是第一次在这个论坛上的用户。 这是我的场景:在用户窗体上,我有一个combobox,两个文本框和一个“确定”button。 当用户从combobox的下拉列表中进行select时,会触发combobox的更改事件,事件处理代码将根据用户select使用工作表中的信息填充文本框。 用户可以在一个或两个文本框中编辑信息。 用户然后点击“确定”。 OKbutton的单击事件然后将修改的信息从文本框写回到工作表中的单元格。 看起来相当简单。 这是我的问题:combobox的更改事件似乎触发每次它的属性被引用。 具体来说,下面的cb_CustomersUpdateOK_Click()子例程中的三个实例引用了combobox的ListIndex属性。 我在更改事件代码中放置了一个Msgbox来指示事件何时触发。 在“确定”单击事件代码中的三个分配语句的每一个上使用断点时,三个语句中的每一个都会触发(Msgbox显示)combobox。 当触发发生时,它将用comboboxselect中的初始数据覆盖文本框中的编辑信息。 (1)为什么combobox更改事件触发它的方式? (2)为防止这种情况发生,我该怎么做?

过去几个小时我一直在研究这个问题,而且我还没有发现任何非常有用的东西。 任何帮助将不胜感激。 请让我知道是否需要更多的信息。

Private Sub combo_CustomersUpdateLastName_Change() MsgBox "combobox changed" 'For debug purposes With Sheets("Customers") tb_CustomersUpdateFirstName.Value = .Cells(combo_CustomersUpdateLastName.ListIndex + 2, 2).Value tb_CustomersUpdatePhone.Value = .Cells(combo_CustomersUpdateLastName.ListIndex + 2, 3).Value End With End Sub ... Private Sub cb_CustomersUpdateOK_Click() 'Copy the updated customer data from the controls to the Customers sheet With Sheets("Customers") .Cells(combo_CustomersUpdateLastName.ListIndex + 2, 1).Value = combo_CustomersUpdateLastName.Value .Cells(combo_CustomersUpdateLastName.ListIndex + 2, 2).Value = tb_CustomersUpdateFirstName.Value .Cells(combo_CustomersUpdateLastName.ListIndex + 2, 3).Value = tb_CustomersUpdatePhone.Value 'Sort the customer data in case the last name or first name was updated Range("CustomerInfo").Sort Key1:=.Columns("A"), Key2:=.Columns("B") End With MsgBox "Customer data updated." Unload form_CustomersUpdate End Sub 

什么是combobox项目的来源? 如果链接到一个范围,则更改事件将被触发,因为写入工作表会更改链接的源代码,这意味着combobox会刷新自身。

如果你不想这样做,那么你需要将范围内的值“caching”到数组中,然后用它们填充combox。

Interesting Posts