1

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

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

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

4

1 回答 1

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 函数会将公式返回的零长度字符串计为空白,而 .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

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

于 2015-07-09T22:04:33.337 回答