[英]VBA - Add item to combobox from dynamically created listview
我需要加載ComboBox3與ListView3中的項目,動態地在ComboBox1中按值更改。
可以這樣做嗎?
Private Sub ComboBox1_Change()
Call filterlist
'This line is what I need to change. Not working in this way
UserForm1.ComboBox3.AddItem = ListView3.ListItems
End Sub
子過濾值:
Private Sub filterlist()
Dim item As ListItem
Dim i As Long
Dim ws As Worksheet
Dim sonsat As Long
Set ws = Sheets("data")
ListView3.ListItems.Clear
sonsat = ws.Cells(Rows.Count, 3).End(xlUp).Row + 1
For i = 2 To sonsat
If ws.Cells(i, 3).Value = ComboBox1.Text Then
Set item = ListView3.ListItems.Add(, , ws.Cells(i, 1))
item.ListSubItems.Add Text:=ws.Cells(i, 2)
item.ListSubItems.Add Text:=ws.Cells(i, 3)
End If
Next i
End Sub
我不是說“恐怖變化”的意思。 我只是在猜測,但請看下一個例子。 如果您的數據結構與圖像一樣,並且您想在ComboBox1中加載A,B和C,並且在combo1中選擇A之后您希望combo2填充101,1010,102等,請嘗試以下代碼。
Private Sub UserForm_Initialize()
Dim dU1 As Object, cU1 As Variant, iU1 As Long, lrU As Long
Dim i As Integer
Set dU1 = CreateObject("Scripting.Dictionary")
lrU = Worksheets("Data").Cells(Rows.Count, 1).End(xlUp).Row
cU1 = Worksheets("Data").Range("A2:A" & lrU) 'Starts in second row. First row left for titles
For iU1 = 1 To UBound(cU1, 1)
dU1(cU1(iU1, 1)) = 1
Next iU1
'now dU1 has unique values from column A
For i = 0 To dU1.Count - 1
ComboBox1.AddItem dU1.Keys()(i) 'Load Combobox1 with unique values from Column A
Next
End Sub
Private Sub ComboBox1_Change()
Dim lLastRow As Long
Dim i As Integer
ComboBox2.Clear
lLastRow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To lLastRow
If Worksheets("Data").Cells(i, 1) = ComboBox1.Text Then
ComboBox2.AddItem (Worksheets("Data").Cells(i, 2))
End If
Next
End Sub
AddItem()方法一次只允許添加一個對象,看起來就像是一次傳遞整個ListView項。 相反,您應該迭代ListView項:
For Each item in ListView3.ListSubItems
ComboBox.AddItem(item.Text)
Next item
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.