VBA - 从动态创建的 ListView 中将项目添加到组合框

标签 vba excel

我需要使用 ListView3 中的项目加载 ComboBox3,这些项目会根据 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,并且在组合 1 中选择 A 后,您希望组合 2 填充 101、1010、102 等,请尝试下面的代码。

enter image description here

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

关于VBA - 从动态创建的 ListView 中将项目添加到组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42346016/

相关文章:

Python:用于运行 Excel VBA 脚本的脚本未运行

excel - 输入什么excel公式

vba - 删除用户表单中动态创建的文本框的问题

excel - 如何在vba中调用已分配给按钮的函数

excel - 关闭窗口

excel - VBA - 公式数组 doe

Python脚本从Excel到文本搜索名称,然后将其相应的值插入到Excel中

vba - `Is` 对于指向同一单元格的两个范围变量,运算符不返回 true

vba - 在多个 Excel 工作表上运行宏

vba - 连接和迭代多个单元格VBA excel