【问题标题】:VBA - Remove empty items from ListBoxVBA - 从列表框中删除空项目
【发布时间】:2020-08-09 13:10:12
【问题描述】:

我想从我用数组创建的 ListBox 中删除空项目。但是,在某些时候,每次更新 ListCount 值时,代码都会失败。我该如何克服这个问题?

Private Sub RemoveEmptyRows(lst As msforms.ListBox)
With lst
    For i = 0 To .ListCount - 1
        If .List(i) = False Then
            .RemoveItem i
        End If
    Next
End With

结束子

【问题讨论】:

    标签: vba listbox listboxitem


    【解决方案1】:

    请尝试下一个代码:

    Private Sub RemoveEmptyRows(lst As msforms.ListBox)
        Dim i As Long
        With lst
            For i = .ListCount - 1 To 0 Step -1
                If .List(i) = Empty Then
                    .RemoveItem i
                End If
            Next
        End With
    End Sub
    

    迭代必须向后进行。否则,删除项目后,它们的引用将丢失...

    这就是为什么您的解决方案(即使不是很有效)也能奏效的原因。每次删除项目后,都会使用所有现有项目的新引用重新开始迭代。

    【讨论】:

      【解决方案2】:

      经过一些调试,我找到了解决方案。我希望这对其他人有帮助。每次我删除一个项目时,随着 ListCount 值的更新,我都会让它回到开头。对性能不好,但它正在工作。

      Private Sub RemoveEmptyRows(lst As msforms.ListBox)
          With lst
      iterate:
              For i = 0 To .ListCount - 1
                  If .List(i) = False Then
                      .RemoveItem i
                      GoTo iterate
                  End If
              Next
          End With
      End Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-07
        • 2010-11-29
        • 1970-01-01
        • 2011-01-17
        • 1970-01-01
        相关资源
        最近更新 更多