Vba excel空白单元错误处理

时间:2016-07-18 23:44:15

标签: excel-vba vba excel

  Sub Remove_Deregistered()

With Worksheets("Sheet2")
For Each cel In .Range(.Range("D2"), .Range("D2").End(xlDown))
   If cel.Value Like "*Deregistered*" Then

       Worksheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1).Value = cel.Offset(, 10).Value
      cel.Resize(1, 1).ClearContents

      Worksheets("Sheet3").Range("B" & Rows.Count).End(xlUp).Offset(1).Value = cel.Offset(, 11).Value
      cel.Resize(1, 1).ClearContents

   End If

 Next

Sheet2.Range(.Range("D2"), .Range("G2").End(xlDown).Offset(, -3)).SpecialCells(xlCellTypeBlanks).EntireRow.Delete


End With

End Sub

在上面的Sub中,当Range D2没有空白单元格时,我在这一行中收到错误:

   Sheet2.Range(.Range("D2"), .Range("G2").End(xlDown).Offset(, -3)).SpecialCells(xlCellTypeBlanks).EntireRow.Delete

如何防止此错误?

2 个答案:

答案 0 :(得分:1)

您可以使用一些错误处理代码,例如:

BeginTry1:
    On Error GoTo ErrHandler1
    Worksheets("Sheet1").Range(.Range("D2"), _
                               .Range("G2").End(xlDown).Offset(, -3)).SpecialCells(xlCellTypeBlanks).EntireRow.Delete

ErrHandler1:
    Debug.Print Err.Description

答案 1 :(得分:1)

或者你可以忽略这样的错误

On Error Resume Next 

' your code that might give error here

If Err.Number <> 0 Then Debug.Print Err.Description  ' optional to print the error in the VBA Immediate window

On Error GoTo 0   ' optional to reset the error handling 

http://www.cpearson.com/excel/errorhandling.htm