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?
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 click a cell and then press DELETE or BACKSPACE, you clear the cell contents without removing any cell formats or cell comments.
There are two shortcuts that you can use Alt + F11 for the VBA Window and Alt + F8 to view macros. Select your work and the module. Your macro should be Sub Clear_cells() range (C1:C11"). clearcontents End Sub.
You can access entire column as a range using the Worksheet.Columns
object
Something like:
Worksheets(sheetname).Columns(1).ClearContents
should clear contents of A column
There is also the Worksheet.Rows
object if you need to do something similar for rows
The error you are receiving is likely due to a missing with block.
You can read about with blocks here: Microsoft Help
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:
ActiveSheet.Range("A3:A" & Range("A3").End(xlDown).Row).ClearContents
Starts on the third row - change to your liking.
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