仅单行数据时的动态范围选择问题

时间:2018-12-03 04:47:33

标签: excel vba

我在Excel VBA代码中使用AdvancedFilter来生成一系列值,然后将这些值动态选择并加载到ListBox中。除非范围内只有1列资料,否则运作良好。在这种情况下,将在ListBox中加载1行值,然后是几行空白值。我该怎么做才能纠正这个问题?

下面的代码和支持的屏幕截图:

Private Sub Condition_Change()

    ConditionDtl.Clear

    If Condition.Value <> "" Then

        'Filter Condition Detail list according to Condition selection
        Set ws5 = Worksheets("CondCondDtl")
        With ws5
            .Range("CritConditionDtl").Cells(2, 1).Value = Condition.Column(0)
            .Range("CritConditionDtl").Cells(2, 2).Value = Condition.Column(1)
            .Columns("A:D").AdvancedFilter Action:=xlFilterCopy, _
                CriteriaRange:=.Range("CritConditionDtl"), CopyToRange:=.Range("CopyConditionDtl"), Unique:=True
        End With
        Set ws5 = Nothing

        'Load the new list of items into multiselect listbox
        ConditionDtl.List = Worksheets("CondCondDtl").Range("I2", _
            Worksheets("CondCondDtl").Range("I2").End(xlToRight).End(xlDown)).Value

    End If

End Sub

AdvanceFilter产生的数据:
Data produced by AdvanceFilter

具有空白列表项的列表框:
ListBox with blank list items

1 个答案:

答案 0 :(得分:1)

类似这样的东西:

With Worksheets("CondCondDtl")
    ConditionDtl.List =  .Range(.Range("I2"), .cells(rows.count, "J").End(xlUp)).Value
End With