1

I'm trying to clean up my spreedsheet. There are many blank cells which are throwing off the count. I tried using this code but it's giving me a run-time error.

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
1
  • Try For each c in MyRange.Cells? Commented Jun 24, 2013 at 19:54

2 Answers 2

3

This error might be triggered because of finding a merged cell (or equivalent). I did some tests and IsEmpty seems to skip these situations. In any case, I am also including an error catching to be completely sure.

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
Sign up to request clarification or add additional context in comments.

3 Comments

+1. Merged cells are difficult to work with, and cause problems especially when iterating over cells in a range, like this.
Is there any way to run this faster? It's taking a really long time to process.
This is a really fast configuration. The only reason I can come up with to explain it being too slow is that the cath part (On Error Resume Next) is actually being used. Error catching is pretty time consuming. But I don't known what might be provoking the errors (comment the aforementioned line and see in which cell it crashes and see what is wrong with this cell). ClearContents shouldn't take too long but I guess that c.Value = "", would be still quicker.
2

Perhaps this: changed c to cells instead of range and used cells collection on the range.

Realized you may need c.value as well. Otherwise what property of the cell are you looking at?

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 Link

1 Comment

.Value is the default property of a cell/range. c = c.Value will return true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.