【问题标题】:Why is a (Excel VBA) combobox change event triggering every time one of its properties is referenced?为什么每次引用其属性之一时都会触发(Excel VBA)组合框更改事件?
【发布时间】:2014-04-20 19:45:16
【问题描述】:

我是这个论坛的第一次用户。这是我的场景:在用户窗体上,我有一个组合框、两个文本框和一个“确定”按钮。当用户从组合框的下拉列表中进行选择时,将触发组合框的更改事件,并且事件处理代码会根据用户选择使用工作表中的信息填充文本框。然后,用户可以在一个或两个文本框中编辑信息。然后用户点击“OK”。然后,确定按钮的单击事件将修改后的信息从文本框中写回工作表中的单元格。似乎相当直截了当。这是我的问题:组合框的更改事件似乎在每次引用其属性时都会触发。具体来说,下面的 cb_CustomersUpdateOK_Click() 子例程中的三个实例引用了组合框的 ListIndex 属性。我在 Change 事件代码中放置了一个 Msgbox,以指示事件何时触发。在 OK 单击事件代码中的三个 assign 语句中的每一个处使用断点,组合框在三个语句中的每一个处触发(显示 Msgbox)。当触发发生时,它会用组合框选择的初始数据覆盖文本框中编辑的信息。 (1) 为什么组合框更改事件会以这种方式触发? (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

【问题讨论】:

    标签: excel vba combobox event-triggers


    【解决方案1】:

    组合框项目的来源是什么?如果它链接到一个范围,则触发更改事件,因为写入工作表会更改链接的源,这反过来意味着组合框会自行刷新。

    如果您不希望发生这种情况,则需要将范围内的值“缓存”到一个数组中,并用它们填充组合框。

    【讨论】:

    • 这正是正在发生的事情,对解决方案进行编码是一件轻而易举的事。不错的收获!
    • 很高兴它有帮助。我一直想念那些有事件触发事件等等的东西;)
    猜你喜欢
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多