删除空行会产生1004错误

时间:2017-06-16 09:29:35

标签: excel vba excel-vba

如果某列中的单元格为空,我想删除行。

我正在使用我找到的示例代码here

最初,有问题的细胞在B栏中。我使用了以下内容:

Sub delrowEmptyStr()

    Dim EmpCol As Range, LstRw As Long
    LstRw = Columns(2).Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlFormulas).Row
    Set EmpCol = Cells.Find(What:="*", SearchOrder:=xlColumns, SearchDirection:=xlPrevious, LookIn:=xlFormulas).Offset(, 1).EntireColumn
    With Intersect(Rows("2:" & LstRw), EmpCol)
        .FormulaR1C1 = "=IF(RC2="""",""X"","""")"
        .Value = .Value
        .SpecialCells(xlConstants).EntireRow.Delete
    End With
End Sub

我重新格式化并将该数据放在A列中。我将Sub更改为以下内容:

Sub delrowEmptyStr()

    Dim EmpCol As Range, LstRw As Long
    LstRw = Columns(1).Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlFormulas).Row
    Set EmpCol = Cells.Find(What:="*", SearchOrder:=xlColumns, SearchDirection:=xlPrevious, LookIn:=xlFormulas).Offset(, 1).EntireColumn
    With Intersect(Rows("2:" & LstRw), EmpCol)
        .FormulaR1C1 = "=IF(RC1="""",""X"","""")"
        .Value = .Value
        .SpecialCells(xlConstants).EntireRow.Delete
    End With
End Sub

现在运行此操作会产生'运行时错误1004:找不到单元格'。

点击'Debug'突出显示行

.SpecialCells(xlConstants).EntireRow.Delete

在运行Sub的第二次迭代之前,我对数据进行了不同的排序 - 我想知道是否可能将所有空单元格放在列底部可能是问题?

1 个答案:

答案 0 :(得分:0)

  

我想知道是否可能有我想要摆脱列底部的所有空单元格可能是问题?

是的,当然,因为声明

LstRw = Columns(1).Find(What:="*", SearchOrder:=xlRows, _
   SearchDirection:=xlPrevious, LookIn:=xlFormulas).Row

LstRw作为该特定列中的最后一个非空行。您可以通过简单地查找整个工作表中的最后一个非空行而不是特定列中的最后一个非空行来解决此问题:

'      vvvvvv
LstRw = Cells.Find(What:="*", SearchOrder:=xlRows, _
   SearchDirection:=xlPrevious, LookIn:=xlFormulas).Row