VBA – 从dynamic创build的列表视图添加项目到combobox

我需要加载ComboBox3与ListView3中的项目,它是由ComboBox1中的值dynamic改变的。

有没有可能做这样的事情?

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 

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 

我不是很确定“dinamically改变”的意思。 我只是猜测,但看下面的例子。 如果你的数据结构是图像,并且你想在你的ComboBox1中加载A,B和C,并且在combo1中selectA之后,你希望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