简体   繁体   中英

How to resolve error 400 in excel-vba

I am writing an excel-vba to find and delete entire row if having blanks cell in a particular column. My macro is working fine if there is at least one blank cell but showing error 400 if there is no blank cell. My code is

Sub GPF_Sign()
Dim i As Integer, n as integer
Dim LROW As Long

    LROW = Sheets("GPF").Range("B200").End(xlUp).Row

    n = Range("D9:D" & LROW).SpecialCells(xlCellTypeBlanks).Cells.Count
    If n > 0 Then
        Range("D9:D" & LROW).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
    End If
End Sub

You can use On Error Resume Next , but this is not a usually recommended approach because it may mask other errors. Instead, try computing n in an error free way:

n = Application.CountIf(Sheets("GPF").Range("D9:D" & LROW), "")

yet another, still better way is to use AutoFilter :

Sub GPF_Sign()
  With Sheets("GPF").Range("D8:D200")
    .AutoFilter 1, ""
    .Offset(1).EntireRow.Delete
    .AutoFilter
  End With
End Sub

The method you are using ".SpecialCells(xlCellTypeBlanks)" is attempting to return a range. If there are no blank cells, the next part ".cells.count" is attempting to count Nothing. That's why it gives you an error.

Since you are already checking if n>0, you could just add On Error Resume Next right above the "n= " line. If there is more code after this, you probably want to put a On Error GoTo 0 after this part so it doesn't ignore later errors.

Take your pick

Way 1: Using OERN (On Error Resume Next)

Sub WAY_ONE()
    Dim ws As Worksheet, LROW As Long
    Dim rng As Range

    Set ws = Sheets("GPF")

    With ws
        LROW = .Range("B" & .Rows.Count).End(xlUp).Row

        On Error Resume Next
        Set rng = .Range("D9:D" & LROW).SpecialCells(xlCellTypeBlanks)
        On Error GoTo 0

        If Not rng Is Nothing Then rng.EntireRow.Delete
    End With
End Sub

Way 2: Using Autofilter

Sub WAY_TWO()
    Dim ws As Worksheet, LROW As Long
    Dim rng As Range

    Set ws = Sheets("GPF")

    With ws
        .AutoFilterMode = False

        LROW = .Range("B" & .Rows.Count).End(xlUp).Row

        Set rng = .Range("D9:D" & LROW)

        With rng 'Filter, offset(to exclude headers) and delete visible rows
            .AutoFilter Field:=1, Criteria1:=""
            .Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        End With

        .AutoFilterMode = False
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM