Excel VBA - 需要删除B列中填充引用错误的单元格值的行

时间:2016-06-02 20:16:16

标签: excel vba excel-vba for-loop

我的代码底部有一个循环,它成功遍历我的数据并清除列H = 0的所有行。

但是,B列中有几个单元显示#REF!。我也希望这个循环以与H列中的0相同的方式删除这些行。

我认为我的问题是不知道如何引用这些类型的错误。像字符串一样处理#REF!似乎不起作用。

谢谢!

Sub test()

Dim currentSht As Worksheet
Dim lastRow As Long
Dim lastCol As Long
Dim startCell As Range
Dim r As Integer

Set startCell = Sheets("Sheet1").Range("A1")
Set currentSht = ActiveWorkbook.Sheets("Sheet1")

lastRow = startCell.SpecialCells(xlCellTypeLastCell).Row    '<~~ Not sure why, but do not use "Set" when defining lastRow
lastCol = startCell.SpecialCells(xlCellTypeLastCell).Column

For r = 1 To lastRow Step -1
    If currentSht.Cells(r, "H").Value = 0 Or currentSht.Cells(r, "B").Text = "#REF!" Then
    Rows(r).Select
    Selection.EntireRow.Delete
End If
Next r

currentSht.Range(startCell, currentSht.Cells(lastRow, lastCol)).Select

End Sub

2 个答案:

答案 0 :(得分:0)

这段代码怎么样:

Sub Delete0()

Dim F As Integer
Dim Y As Integer
Dim RngCount As Range


Set RngCount = ActiveSheet.Range("H:H")
Y = Application.WorksheetFunction.CountA(RngCount)

For F = Y To 1 Step -1

If IsError(ActiveSheet.Range("H" & F)) Then
ActiveSheet.Rows(F).EntireRow.Delete
ElseIf ActiveSheet.Range("H" & F).Value = 0 Then
ActiveSheet.Rows(F).EntireRow.Delete
End If


Next F

End Sub

答案 1 :(得分:0)

我想我看到了你的问题:

 For r = 1 To lastRow Step -1

将该行更改为

For r = lastrow to 1 Step -1