Search code examples
excelvba

Why is my macro to delete rows with specific criteria not working?


Am I using incorrect Dim statements? The macro runs, but it does not delete anything.

Below is the coding:

Sub DeleteRowsonCriteria()

    Dim lastRow As Long, dataRow As Long
    Dim prodTran As String, prodTran2 As String, prodOIS As String, prodOIS2 As String
    
    lastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
    
    For dataRow = lastRow To 3 Step -1
    
        prodTran = Range("A" & dataRow).Text
        prodTran2 = Range("A" & dataRow).Text
        prodOIS = Range("AA" & dataRow).Text
        prodOIS2 = Range("AA" & dataRow).Text
        
        If prodTran = "Ordered" And prodTran2 = "Cancelled" And prodOIS = "Cancelled" And prodOIS2 = "Refund" Then
        
            Rows(dataRow).Delete
            
        End If
        
    Next dataRow

End Sub

Solution

  •     Sub DeleteRowsonCriteria()
    
        Dim lastRow As Long, dataRow As Long
        Dim prodTran As String, prodOIS As String
        '===Start checking condition from Last row upwards so that when deleting it won't shift cells that are unchecked==='
        lastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
        
        For dataRow = lastRow To 3 Step -1  'User do not want want to delete row 1 and 2 so checking will stop at row 3, checking will start at the last row and move up (-1).
        
            prodTran = Range("A" & dataRow).Text
            prodOIS = Range("AA" & dataRow).Text
            '===As soon as any If condition is satisfied, it will delete the row and go straight to "End if" section, otherwise it will check the next "ElseIF" condition below it and do the same===".
            If prodTran = "Ordered" Then
               Rows(dataRow).Delete    
              
                ElseIf prodTran = "Cancelled" Then
                Rows(dataRow).Delete
                
                ElseIf prodOIS = "Cancelled" Then
                Rows(dataRow).Delete
                
                ElseIf prodOIS = "Refund" Then
                Rows(dataRow).Delete
                
            End If
            
        Next dataRow  'This is for the checking the next row moving up (Looping) .
    
    End Sub