[英]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$1:index(Inventory!$A:$A;CountA(Inventory!$A:$A))"
MsgBox "Item has been removed.", vbOKOnly
End Sub
我認為,最好創建一個單獨的方法來填充combobox
,然后可以從Initialize
事件中調用該combobox
,並且無論何時應更新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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.