如何启用Excel VBAcombobox自动更新

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

我创build了一个combobox来删除选定的项目,但我不知道如何删除某个项目后更新列表。 我正在使用下面的代码来执行删除和刷新functionionality。

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$1:index(Inventory!$A:$A;CountA(Inventory!$A:$A))" MsgBox "Item has been removed.", vbOKOnly End Sub 

在我看来,最好创build一个单独的方法来填充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