Search code examples
vbaexcelisnumeric

Delete row if first cell isn't numeric vba Excel


I am using following code to delete a row if the first cell is not a number (text or blank cell)

Dim LR3 As Long, i3 As Long
With Sheets("Productos")
LR3 = Range("A" & Rows.Count).End(xlUp).Row
For i3 = LR3 To 2 Step -1
    If IsNumeric(Sheets("Productos").Range("A" & i3).Value) Then
    Else
    Rows(i3).Delete
    End If
Next i3
End With

LR3 to 2 is used because the first row is a header row, and I don't want it deleted. I don't see anything wrong with the code, and I even get no error. Do you see something wrong? It´s maybe a false procedure?


Solution

  • The problem with your code which I suspect is that Sheets("Productos") is not the activesheet. So Rows(i3).Delete is referring to the activesheet which might not be Sheets("Productos")

    Notice the use of DOTS in the code below.

    Try this (TRIED AND TESTED)

    Sub Sample()
        Dim LR3 As Long, i3 As Long
    
        With Sheets("Productos")
            LR3 = .Range("A" & .Rows.Count).End(xlUp).Row
    
            For i3 = LR3 To 2 Step -1
                If Not IsNumeric(.Range("A" & i3).Value) Then .Rows(i3).Delete
            Next i3
        End With
    End Sub
    

    EDIT: I missed the Blank Cell part but thanks to Jimmy's post, I saw that.

    Amended Code

    Sub Sample()
        Dim LR3 As Long, i3 As Long
    
        With Sheets("Productos")
            LR3 = .Range("A" & .Rows.Count).End(xlUp).Row
    
            For i3 = LR3 To 2 Step -1
                If Not IsNumeric(.Range("A" & i3).Value) Or _
                .Range("A" & i3).Value = "" Then .Rows(i3).Delete
            Next i3
        End With
    End Sub