VBA列表框添加的异常行为

时间:2018-11-01 12:21:52

标签: excel vba excel-vba

我编写了一个VBA程序来运行,以添加Excel工作表可见范围内的项目列表。请参见下面的代码:

Dim LR, LRR As Integer
Dim FilterArea As Range
Dim oneCell As Variant
Dim FiltCount As Integer
LR = Sheet2.Range("A" & Rows.Count).End(xlUp).Row
Sheet2.Cells.AutoFilter
UserFrom3.ListBox1.Clear
FiltCount = 0

'AutoFiltering the FilterArea
With Sheet2.Range("A2:N" & LR)

    If (UserFrom3.ComboBox3 <> "") Then
        FiltCount = 1
        .AutoFilter _
        Field:=4, _
        Criteria1:=UserFrom3.ComboBox3
    End If

    If (UserFrom3.ComboBox1 <> "") Then
        FiltCount = 1
        .AutoFilter _
        Field:=5, _
        Criteria1:=UserFrom3.ComboBox1
    End If

    If (UserFrom3.TextBox1 <> "") Then
        FiltCount = 1
        .AutoFilter _
        Field:=8, _
        Criteria1:="*" & UserFrom3.TextBox1.Text & "*"
    End If
End With



If FiltCount = 1 Then
    With UserFrom3.ListBox1
        .ColumnCount = 7
        .ColumnHeads = False
        .ColumnWidths = "50,35,50,50,75,89,100"


        For Each oneCell In Sheet2.Range("A2:A" & LR).SpecialCells(xlCellTypeVisible)
            .AddItem CStr(oneCell.Value)
            .List(.ListCount - 1, 1) = oneCell.Offset(0, 1).Value
            .List(.ListCount - 1, 2) = oneCell.Offset(0, 2).Value
            .List(.ListCount - 1, 3) = oneCell.Offset(0, 3).Value
            .List(.ListCount - 1, 4) = oneCell.Offset(0, 4).Value
            .List(.ListCount - 1, 5) = oneCell.Offset(0, 5).Value
            .List(.ListCount - 1, 6) = oneCell.Offset(0, 6).Value
        Next oneCell

    End With
End If

End Sub

每当我向UI提供有效输入时,上面的代码都可以正常工作。它返回结果。当没有要过滤的内容时。即,当过滤结果为零时。除标题(在excel和listbox中)外,零行是可见的。

但是在出现零行可见情况之后,我在下一次搜索中遇到错误。列表框会加载除我的范围外的所有不需要的数据(即,它显示其他范围内的值)并显示代码错误

.List(.ListCount - 1, 6) = oneCell.Offset(0, 6).Value

错误消息是“运行时错误1004-应用程序定义或对象定义的错误。”

有人可以告诉我什么问题吗?

1 个答案:

答案 0 :(得分:0)

插入以下代码。

Dim Ws As Worksheet
Set Ws = Sheet2
If Ws.FilterMode Then
    Ws.ShowAllData
End If