Search code examples
vbafor-looplistobject

Delete row in for loop if meets criteria


I want to delete a row once I've copied it to another location. There are lots of posts for this issue; I'm not sure why none of them are working in my specific situation.

Sub Transition_Queue_to_Other()

Dim QueueSheet As Worksheet
Set QueueSheet = ThisWorkbook.Worksheets("Project Queue")

Dim TableQueue As ListObject
Set TableQueue = QueueSheet.ListObjects("TableQueue")

Dim TransColumn As Range
Set TransColumn = QueueSheet.Range("TableQueue[Transition]")

Dim Trans_Queue_Row As Range
Dim i As Integer

With TransColumn
    For i = 1 To .Count

        If InStr(1, .Rows(i).Value, "NPD") > 0 Then

            Dim NPDSheet As Worksheet
            Set NPDSheet = ThisWorkbook.Worksheets("NPD")

            Dim TableNPD As ListObject
            Set TableNPD = NPDSheet.ListObjects("TableNPD")

            Set Trans_Queue_Row = TableQueue.DataBodyRange.Rows(i)
            Set Trans_NPD_Row = TableNPD.ListRows.Add.Range

            Trans_NPD_Row.Cells(, 1).Value = Trans_Queue_Row.Cells(, 2).Value

'Now, how do I delete each Trans_Queue_Row after I've copied the info from it to the Trans_NPD_Row?  I've tried several different ways with no success, including:

'Trans_Queue_Row.Delete

'Trans_Queue_Row.Range.Delete

'Trans_Queue_Row.Select
'Selection.Delete

Solution

  • Try this Code:

    Sub Transition_Queue_to_Other()
    
    Dim QueueSheet As Worksheet
    Set QueueSheet = ThisWorkbook.Worksheets("Project Queue")
    
    Dim TableQueue As ListObject
    Set TableQueue = QueueSheet.ListObjects("TableQueue")
    
    Dim TransColumn As Range
    Set TransColumn = QueueSheet.Range("TableQueue[Transition]")
    
    Dim Trans_Queue_Row As Range
    Dim i As Integer
    
    
                Dim NPDSheet As Worksheet
                Set NPDSheet = ThisWorkbook.Worksheets("NPD")
    
                Dim TableNPD As ListObject
                Set TableNPD = NPDSheet.ListObjects("TableNPD")
    
    
    
    With TransColumn
        For i = .Count To 1 Step -1
    
            If InStr(1, .Rows(i).Value, "NPD") > 0 Then
    
                Set Trans_Queue_Row = TableQueue.DataBodyRange.Rows(i)
                Set Trans_NPD_Row = TableNPD.ListRows.Add.Range
    
                Trans_NPD_Row.Cells(, 1).Value = Trans_Queue_Row.Cells(, 2).Value
    
                Trans_Queue_Row.EntireRow.Delete xlShiftUp
    
            End If
        Next
    End With
    
    End Sub
    

    Going from bottom to Up and deleting the Row using EntireRow.Delete