使用组合框过滤列表框

问题描述 投票:0回答:1

我有一个列表框,显示输入到数据库表中的每条记录。我想使用与特定列中的值匹配的组合框来过滤这些记录。该列存储一个区域。我用所有区域填充了组合框,但是当我选择一个区域来显示包含该特定区域的记录时,出现错误。

Private Sub UserForm_Initialize()
    
    Dim areas() As String
    areas = Split("Assy, PPW, Coils, THS, THP, M/A, Machine Center, Tool Room, Maintenance", ", ")
    
    Dim area As Variant
    For Each area In areas
        cmbAreaFilter.AddItem area
        
    Next area
    
End Sub
Private Sub cmbAreaFilter_Change()
    
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Database")
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).row
    
    Dim i As Long
    For i = 2 To lastRow
        If ws.Cells(i, "B").Value = cmbAreaFilter.Value Then
            With frmOpenRecords.lstOpenRecords
                .AddItem
                .List(.ListCount - 1, 0) = ws.Cells(i, "A").Value
                .List(.ListCount - 1, 1) = ws.Cells(i, "B").Value
                .List(.ListCount - 1, 2) = ws.Cells(i, "C").Value
                .List(.ListCount - 1, 3) = ws.Cells(i, "D").Value
                .List(.ListCount - 1, 4) = ws.Cells(i, "E").Value
                .List(.ListCount - 1, 5) = ws.Cells(i, "F").Value
                .List(.ListCount - 1, 6) = ws.Cells(i, "G").Value
                .List(.ListCount - 1, 7) = ws.Cells(i, "H").Value
                .List(.ListCount - 1, 8) = ws.Cells(i, "I").Value
                .List(.ListCount - 1, 9) = ws.Cells(i, "J").Value
                .List(.ListCount - 1, 10) = ws.Cells(i, "K").Value
                .List(.ListCount - 1, 11) = ws.Cells(i, "L").Value
                .List(.ListCount - 1, 12) = ws.Cells(i, "M").Value
                .List(.ListCount - 1, 13) = ws.Cells(i, "N").Value
                
            End With
        End If
    Next i
          
End Sub

上面的代码是我必须尝试使 ComboBox 工作的代码。当我在组合框中选择一个区域时收到的错误消息是:“权限被拒绝”。当我单击“调试”时,它会突出显示这一行“.AddItem”。如果有人可以帮助解决这个问题,我将不胜感激。

excel vba combobox listbox
1个回答
0
投票

使用以下代码填充ComboBox;

Private Sub UserForm_Initialize()
    Dim areas As Variant
    
    areas = Array("Assy", "PPW", "Coils", "THS", "THP", "M/A", "Machine Center", "Tool Room", "Maintenance")
    cmbAreaFilter.List = areas
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.