Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear contents of cells in VBA using column reference

Tags:

excel

vba

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?

like image 572
dojogeorge Avatar asked Oct 25 '13 15:10

dojogeorge


People also ask

How do you clear cell data in Excel VBA?

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”.

How do you clear the contents of a cell range?

If you click a cell and then press DELETE or BACKSPACE, you clear the cell contents without removing any cell formats or cell comments.

How do I remove contents from a macro in Excel?

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.


2 Answers

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

like image 197
Sam Avatar answered Sep 18 '22 18:09

Sam


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.

like image 30
Eric Sloan Avatar answered Sep 21 '22 18:09

Eric Sloan