Search code examples
excelvbaloopsdelete-row

Skipping single line of code in loop: entirerow.delete in another workbook


Fairly new to VBA, but I am trying to import (copy/paste) data from a selected workbook into my master workbook(holds code), but first need to delete unusable rows in the selected workbook.

If Column C is empty, then I want to delete the entirerow, using a bottom to the top loop, before I copy the data into my master workbook (hence the need to more explicitly refer to each wb).

It's currently skipping "wb.Sheets(1).Rows(r).EntireRow.Delete" line of code within my loop, but executing the loop the correct amount of times. Please help , still learning.

Earlier, it was incorrectly deleting every row: when my if then clause referred to a a different cell (one with a value, not a blank, in it).

Dim wb As Workbook
Dim r As Integer

With wb.Sheets(1)       
     For r = wb.Sheets(1).UsedRange.Rows.Count To 1 Step -1
         If wb.Sheets(1).Cells(r, "C") = "0" Then
             wb.Sheets(1).Rows(r).EntireRow.Delete 
         End If
     Next

Solution

  • Something like this should work. You've used a With block for the code but then not actually used it. You don't need the additional references to the same object. In this I've tested for whether the cell is empty of not using IsEmpty

    Dim wb As Workbook
    Dim r As Integer
    
    With wb.Sheets(1)
        For r = .UsedRange.Rows.Count To 1 Step -1
            If IsEmpty(.Cells(r, 3)) Then
                .Rows(r).Delete
            End If
        Next
    End With