Excel错误1004 – 运行时错误“1004”应用程序定义或对象定义的错误

我试图清理我的spreedsheet。 有很多空白的细胞正在抛弃计数。 我试着使用这个代码,但它给我一个运行时错误。

Sub ClearAll() Dim c As Range, MyRange As Range Set MyRange = Range("A1:JS87") For Each c In MyRange If Len(c) = 0 Then c.ClearContents Next c End Sub 

这个错误可能是由于find一个合并单元格(或等价的)而触发的。 我做了一些testing,IsEmpty似乎跳过了这些情况。 无论如何,我还包括一个错误捕捉是完全确定的。

 Sub ClearAll() Dim c As Range, MyRange As Range Set MyRange = Range("A1:JS87") For Each c In MyRange On Error Resume Next If (Not IsEmpty(c.Value)) Then If Len(c) = 0 Then c.ClearContents End If Next c End Sub 

也许是这样的:将c改为单元格而不是范围,并使用单元格范围内的集合。

意识到你也可能需要c.value。 否则,你在看什么细胞的属性?

 Sub ClearAll() Dim c As cell, MyRange As Range Set MyRange = Range("A1:JS87") For Each c In MyRange.cells If Len(c.value) = 0 Then c.ClearContents Next c End Sub 

MSFT链接