如何启用 Excel vba 组合框自动更新

How to enable Excel vba combobox to update automatically

我正在创建一个处理学校项目库存的用户表单。

我创建了一个组合框来删除选定的项目,但我不知道如何在删除某个项目后更新列表。我正在使用以下代码来执行删除和刷新功能。

Private Sub cmdDelete_Click()
    Dim row As Long
    row = cbPCodeIM.ListIndex + 2

    Sheets("Inventory").Select
    Sheets("Inventory".Range("A" & row & ":E" & row).Select
    Selection.Delete shift:=x1Up
    'the following line does not seem to work when uncommented
    'cbPCodeIM.ListFillRange = "=Inventory!$A:index(Inventory!$A:$A;CountA(Inventory!$A:$A))"
    MsgBox "Item has been removed.", vbOKOnly
End Sub

在我看来,最好创建一个单独的方法来填充 combobox,然后您可以从 Initialize 事件调用该方法,也可以在需要更新 combobox 时调用.

userform 背后的代码如下所示,包含捕获 cmdDelete-Click() 事件、Userform_Initialize() 事件和最后自定义方法的代码。

如有任何问题,请告诉我。

Private Sub cmdDelete_Click()
    Dim nRow As Long

    nRow = Me.cbPCodeIM.ListIndex + 2
    Worksheets("Inventory").Rows(nRow).Delete 'NOTE, this will delete the entire row

    Fill_My_Combo Me.cbPCodeIM

End Sub

Private Sub UserForm_Initialize()
    Fill_My_Combo Me.cbPCodeIM
End Sub


Private Sub Fill_My_Combo(cbo As ComboBox)
    Dim wsInventory As Worksheet
    Dim nLastRow As Long
    Dim i as Long

    Set wsInventory = Worksheets("Inventory")
    nLastRow = wsInventory.Cells(Rows.Count, 1).End(xlUp).Row ' Finds last row in Column 1

    cbo.clear
    For i = 2 To nLastRow 'start at row 2, assuming a header
        cbo.AddItem wsInventory.Cells(i, 1)
    Next i
End Sub