Excel 代码不断崩溃,但代码中没有错误,应用程序定义或对象定义的错误

Excel Code keeps crashing but no Error in code, Application-Definded or object defined error

我正在编写一个用户表单,其中有一个列表框,当用户选择列表框中的项目时,它会转到数据表中的行范围并将其从 table(称为数据的列表对象)中删除.问题是我不断收到突出显示的代码行的运行时错误。我已经在线阅读但不确定如何解决问题,错误提示应用程序定义或对象定义错误。

我试图改变我引用 table 的方式,但它仍然不起作用

Private Sub Delete_Click()
Dim i As Integer
Dim tabl As ListObject
Set tabl = ShNewDAt.ListObjects("Data")

 For i = 0 To tabl.ListRows.Count
    If ListBoxDisplay.Selected(i) Then
        tabl.ListRows(i).Delete         ' THIS LINE GIVES AN ERROR
    End If
 Next i

End Sub

注释行给出了错误

对象集合希望 使用For Each 循环迭代。 ListObject.ListRows 就是这样一个对象集合。

循环很有可能抛出 index out of bounds 错误:你正在基于 ListRows.Count 进行迭代,但主要驱动因素是 ListBoxDisplay.

通过使用 For Each 循环,您可以避免在迭代时修改集合而导致的问题,因为集合不会在每次迭代时得到 re-evaluated。另一方面,使用 For 循环,您将删除 i 处的行,但这样做会抵消下面的行,并导致行被删除......这是不应该的。但这忽略了对象集合从索引 1 开始,而不是 0:如果 ListBoxDisplay.Selected(0) 为真,则在 .ListRows(i).

处会出现错误 1004

解决此问题的一种方法是将知道要删除哪些行删除需要删除的行这两个问题分开:

Dim toDelete As Collection
Set toDelete = New Collection

Dim currentRow As ListRow
For Each currentRow In table.ListRows
    If ListBoxDisplay.Selected(currentRow.Index - 1) Then
        toDelete.Add currentRow
    End If
Next

For Each currentRow In toDelete
    currentRow.Delete
Next