使用VBA删除Excel中的空行
我正在尝试使用以下代码删除空行:
worksheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
上面的代码工作正常,但给出运行时错误'1004':未找到单元格。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当没有空白单元格时,错误处理会有所帮助。如果没有这样的单元格,
SpecialCells(xlCellTypeBlanks)
将始终返回错误,因此如果您想使用SpecialCells( xlCellTypeBlanks)
。The error handling helps when there are no blank cells.
SpecialCells(xlCellTypeBlanks)
will always return an error if there are no cells like that so error handling is the only way (that I know of) to deal with it if you want to useSpecialCells(xlCellTypeBlanks)
.您需要测试是否有任何空白。
如果没有空格,您可以使用 On Error Resume Next 跳过该行,但通常最好测试特定条件,而不是假设您知道错误是什么。
据我所知,如果 A 列中的每个单元格都有值,您只会收到“未找到单元格”消息。
编辑:根据 @brettdj 的评论,这里有一个仍然使用 CountBlank 的替代方案:
当然,UsedRange 是出了名的变化无常,并且可能比看起来更大。我认为最好首先确定要删除行的实际范围,然后检查该范围内的特殊单元格,例如:
最后一点 - 我将变量从“worksheet”更改为“ws”,因为“worksheet”是Excel 保留字。
You need to test that there are any blanks.
You can just use On Error Resume Next to skip over the line if there are no blanks, but it's generally preferable to test for a specific condition, rather than assuming you know what the error will be.
As far as I can see you'd only get the "No Cells Found" message if every cell in Column A has a value.
EDIT: Based on @brettdj's comments, here's an alternative that still uses CountBlank:
Of course UsedRange is notoriously fickle and may be bigger than it appears. I think it's best to first determine the actual range where the rows are to be deleted and then check the SpecialCells in that range, e.g.:
One last note - I changed the variable from "worksheet" to "ws" as "worksheet" is an Excel reserved word.
和我一起工作很好。这些声明不会向我抛出任何错误
我找到了您问题的这些类型的解决方案
看看这些链接
http://www.excelforum.com/excel-programming/390329-microsoft-visual-basic-run-time-error-1004-no-cells-were-found.html
< a href="http://www.mrexcel.com/forum/showthread.php?t=343744" rel="nofollow">http://www.mrexcel.com/forum/showthread.php?t=343744
是的,您设置了对象吗?工作表在这里没有任何意义
Working fine with me . These statement does not throw any error to me
I found these type of solution for your question
Take a look at these links
http://www.excelforum.com/excel-programming/390329-microsoft-visual-basic-run-time-error-1004-no-cells-were-found.html
http://www.mrexcel.com/forum/showthread.php?t=343744
and well yes did you set your object ? worksheet does not make any sense here
另一种方式:
Another way: