1

I'm trying to delete the lines of a TEAMS Table when the Value2 of column D does not match a variable department (String). I'm able to detect the rows I want to delete, but the delete method causes a "delete method of range class failed" error.

Here is a simplified code snippet.

Dim i As Integer
For i = 1 To wkbook.Worksheets("T").Range("TEAMS").Rows.Count
  With wkbook.Worksheets("T").Range("TEAMS[D]")(i)
    If .Value2 <> department Then
      .EntireRow.Delete
    End If
  End With
Next i
1
  • Possiblyy a standard row delete issue where you should loop from the bottom to the top. Try: For i = wkbook.Worksheets("T").Range("TEAMS").Rows.Count To 1 Step -1 Commented Sep 10, 2019 at 16:34

1 Answer 1

2

You're in a ListObject/table - use the ListObject API.

Dim table As ListObject
Set table = wkbook.Worksheets.ListObjects("TEAMS")

Dim colIndex As Long
Set colIndex = table.ListColumns("D").Index

Dim toDelete As Range

Dim currentRow As ListRow
For Each currentRow In table.ListRows
    If currentRow.Range.Cells(ColumnIndex:=colIndex).Value <> department Then
        If toDelete Is Nothing Then
            Set toDelete = currentRow.Range
        Else
            Set toDelete = Application.Union(toDelete, currentRow.Range)
    End If
Next

If Not toDelete Is Nothing Then toDelete.Delete

Pretty similar to this answer.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm assuming that it should be Table.ListRows, no?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.