I am trying to get a piece of code to clear the data in some cells, using the column references. I am using the following code:
Worksheets(sheetname).Range(.Cells(2, LastColData), .Cells(LastRowData, LastColData)).ClearContents
To do this, however I am getting an error at the first .Cells section, why is this?
For anyone like me who came across this and needs a solution that doesn't clear headers, here is the one liner that works for me:
Starts on the third row - change to your liking.
As Gary's Student mentioned, you would need to remove the dot before
Cells
to make the code work as you originally wrote it. I can't be sure, since you only included the one line of code, but the error you got when you deleted the dots might have something to do with how you defined your variables.I ran your line of code with the variables defined as integers and it worked:
I don't think a
With
statement is appropriate to the line of code you shared, but if you were to use one, theWith
would be at the start of the line that defines the object you are manipulating. Here is your code rewritten using an unnecessaryWith
statement:With
statements are designed to save you from retyping code and to make your coding easier to read. It becomes useful and appropriate if you do more than one thing with an object. For example, if you wanted to also turn the column red and add a thick black border, you might use aWith
statement like this:Otherwise you would have to declare the range for each action or property, like this:
I hope this gives you a sense for why Gary's Student believed the compiler might be expecting a
With
(even though it was inappropriate) and how and when aWith
can be useful in your code.