简体   繁体   中英

Vba clear contents of a certain range or cell

How can I clear the column and row starting with a reference cell?

I used

For x = 1 To 20 
    Sheets(1).Columns(x).ClearContents
Next x

But I want to be able to clear the contents of all rows and columns starting with row A6 as a reference point. I cant use range since the data is dynamic and changes upon insertion of data. The data came from a csv

Since your question states "I want to be able to clear the contents of all rows and columns starting with row A6 as a reference point." Then here is a one liner using SpecialCells(xlLastCell)

ActiveSheet.Range("A6", ActiveCell.SpecialCells(xlLastCell)).Clear

If your range starts at A6 and is continuous with no blanks in Row 6 and no blanks in Column A , you could set the range like this:

'Create variables
Dim wb as Workbook
Dim ws as Worksheet
Dim rng as Range

'Initialize variables
set wb = ActiveWorkbook
set ws = ActiveSheet
lastrow = ws.Range("A6").End(xlDown).Row
lastcol = ws.Range("A6").End(xlToRight).Column

'Set the range
set rng = ws.Range(Cells(6,1),Cells(lastrow,lastcol))

'Clear contents
rng.ClearContents

This uses Range.End property of the Range object. It's basically like clicking on A6 and hitting ctrl+right on your keyboard and then returning the range.

Note: If there are gaps in the range you won't get the correct result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM