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

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

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

我应该尝试包括一个如果然后声明来抵消这一点? 提前致谢!

有几个方法去处理试图删除不存在的东西的潜在错误。

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

 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函数会计算由公式返回的零长度string作为空白,而不会被.SpecialCells(xlCellTypeBlanks)方法视为空白。 然而,你可能不会在你知道填充公式的列中寻找空白,所以这是一个考虑,而不是一个交易断路器。

接下来,我们可以通过改变error handling方法来testingNothing

 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 

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