当我的工作簿中没有空白单元格时,我的代码停止了

时间:2015-07-09 20:49:36

标签: excel vba blank-line

我正在创建一些vba代码,它可以自动删除合并的单元格,然后删除由于异议而创建的空白行。当选项卡没有任何空值时,问题就出现了。当工作表没有任何空白值时,我收到错误9.下面是检测和删除文档中空白行的代码:

Range("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

我应该尝试包含if then语句来抵消这种情况吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

有几种方法可以解决尝试删除不存在的错误的潜在错误。

首先,您可以检查是否有空白单元格。

with worksheets("Sheet1")
    with .range(.cells(1, 1), .cells(rows.count, 1).end(xlup))
        if cbool(application.countblank(.columns(1))) then
            .cells.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
        end if
    end with
end with

'earlier version of Excel may not have COUNTBLANK
with worksheets("Sheet1")
    with .range(.cells(1, 1), .cells(rows.count, 1).end(xlup))
        if application.counta(.columns(1)) < .rows.count then
            .cells.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
        end if
    end with
end with

上面的缺点是COUNTBLANK function会将公式返回的零长度字符串计为空白,而.specialCells(xlCellTypeBlanks)方法不会将它们视为空白。但是,你可能不会在你知道填充公式的列中寻找空白,所以这是一个考虑因素,而不是交易破坏者。

接下来,我们可以通过更改错误处理方法来测试 Nothing

dim delRng as range
with worksheets("Sheet1")
    with .range(.cells(1, 1), .cells(rows.count, 1).end(xlup))
        'temporarily suspend error handling
        on error resume next
        set delRng = .cells.SpecialCells(xlCellTypeBlanks)
        on error goto 0
        if not delRng  is nothing then
            delRng.EntireRow.Delete
        end if
    end with
end with

虽然被广泛接受,但我不赞成这种方法,因为我认为你不应该为了看它是否存在而破坏某些东西,但这只是我个人的偏好。

相关问题