Search code examples
excelvbaloopsrow

Check if cell is text and if so, delete row


UPDATE:

Data set is made of strings that are number though (I don't get it) -> I can do all the math stuff with them as with regular numbers.

Problem is I need to separate cells that look like this "186.85" and cells that look like this "1.76 Dividend".

====================

I need a loop to check row by row if the cell contains some text (word "dividend" specifically) or if it's just number. If it is a text, then delete it and move to the next row.

It does some deleting BUT it wipes like 50 rows of data almost every time (I have only two text populated rows in this particular data set). These rows are numbers.

Dim i As Long
i = 2

Do
    If WorksheetFunction.IsText(Sheets("Data").Cells(i, 5)) = True Then
        If Not Worksheets("Data").Cells(i, 5).Value = "" Then
            Worksheets("Data").Rows(i).Delete
        End If
    End If
    i = i + 1
Loop Until i = 100

I expected to loop through the data and delete the entire row if a cell contains text.

This code so far deletes things kinda randomly.


Solution

  • The below has been updated to a dynamic range. This will not need modification regardless of how many rows your sheet has.

    More importantly, deleting rows inside a loop will cause your range to shift at every deletion. The way around this is to loop backwards

    OR, even better..

    Don't delete cells inside your loop. Every time your criteria is met, you force an action (deletion). Instead, gather up all of the cells to be deleted inside your loop and then delete the entire collection (Union) all at once outside of the loop. This requires 1 action in total rather 1 action per text instance


    Sub Looper()
    
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1") '<-- Update sheet name
    Dim i As Long, LR As Long
    Dim DeleteMe As Range
    
    LR = ws.Range("E" & ws.Rows.Count).End(xlUp).Row
    
    For i = 2 To LR
        If WorksheetFunction.IsText((ws.Range("E" & i))) Then
            If Not DeleteMe Is Nothing Then
                Set DeleteMe = Union(DeleteMe, ws.Range("E" & i))
            Else
                Set DeleteMe = ws.Range("E" & i)
            End If
        End If
    Next i
    
    If Not DeleteMe Is Nothing Then DeleteMe.EntireRow.Delete
    
    End Sub