Good evening friends:
I have in mind 2 ways for clearing a content in a defined range of cells of a VBA project (in MS Excel):
Worksheets("SheetName").Range("A1:B10").ClearContents
Worksheets("SheetName").Range(Cells(1, 1), Cells(10, 2)).ClearContents
The problem is that the second way show me an error '1004' when I'm not watching the current Worksheet "SheetName" (in other words, when I haven't "SheetName" as ActiveSheet).
The first way work flawlessly in any situation.
Why does this happen? How can I use the "Second way" without this bug?
ClearContents Method In VBA, there is a method called ClearContents that you can use to clear values and formulas from a cell, range of cells, and the entire worksheet. To use this method, first, you need to define the expression somewhere you want to clear the content, and then type “. ClearContents”.
If you wish to test whether a worksheet cell is empty in VBA, you can not use the worksheet function called ISBLANK. In VBA, you must use the ISEMPTY function. In this example, we will test whether cell A1 is empty. If cell A1 is empty, the message "Cell A1 is empty" will be displayed.
It is because you haven't qualified Cells(1, 1)
with a worksheet object, and the same holds true for Cells(10, 2)
. For the code to work, it should look something like this:
Dim ws As Worksheet
Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
Alternately:
With Sheets("SheetName")
Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range
also, like so:
ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
or
With Sheets("SheetName")
.Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With