用条件填充列表框

时间:2019-05-03 20:35:07

标签: excel vba excel-formula

我从一个范围填充了一个列表框,它显示如下

enter image description here

使用以下代码:

    Private Sub UserForm_Initialize()
    Dim rngOneColumn As Range


    'Define the source range
    Set rngOneColumn = ThisWorkbook.Worksheets("config").Range("E2:E21")

    'Populate listbox item
    ListBox1.List = rngOneColumn.Cells.Value


End Sub

这将从以下工作表中填充。

enter image description here

但是,我要显示的是两列:“房间和未成年人”

,然后仅在房间使用中列(J)等于false的列表框中列出房间号,并在第二列中显示房间未成年人是(F)列中的是还是否。

1 个答案:

答案 0 :(得分:1)

鉴于您的设置,这样的设置应该对您有用:

Private Sub UserForm_Initialize()

    Dim wsConf As Worksheet
    Dim aData As Variant
    Dim aOpenRooms As Variant
    Dim ixData As Long
    Dim ixOpen As Long
    Dim lRoomUseCol As Long
    Dim lRoomInterpsCol As Long
    Dim lRoomMinorCol As Long

    'Adjust these as needed for your data
    Set wsConf = ThisWorkbook.Worksheets("config")
    lRoomUseCol = 10    'column J
    lRoomInterpsCol = 5 'column E
    lRoomMinorCol = 6   'column F

    With wsConf.Range("A1").CurrentRegion
        ReDim aOpenRooms(1 To WorksheetFunction.CountIf(Intersect(.Parent.Columns(lRoomUseCol), .Cells), False), 1 To 2)
        aData = .Value
    End With

    For ixData = LBound(aData, 1) To UBound(aData, 1)
        If aData(ixData, lRoomUseCol) = False Then
            ixOpen = ixOpen + 1
            aOpenRooms(ixOpen, 1) = aData(ixData, lRoomInterpsCol)
            aOpenRooms(ixOpen, 2) = aData(ixData, lRoomMinorCol)
        End If
    Next ixData

    With Me.ListBox1
        .Clear
        .ColumnCount = UBound(aOpenRooms, 2)
        .List = aOpenRooms
    End With

End Sub