简体   繁体   English

VBA清除一定范围或单元格中的内容

[英]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. 但是我希望能够清除以A6行为参考点的所有行和列的内容。 I cant use range since the data is dynamic and changes upon insertion of data. 我不能使用范围,因为数据是动态的,并且在插入数据时会发生变化。 The data came from a csv 数据来自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." 由于您的问题是“我希望能够清除以A6行为参考点的所有行和列的内容”。 Then here is a one liner using SpecialCells(xlLastCell) 然后这是一个使用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: 如果您的范围从A6开始并且连续, Row 6没有空白,而在Column A没有空白,则可以这样设置范围:

'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. 这使用Range对象的Range.End属性。 It's basically like clicking on A6 and hitting ctrl+right on your keyboard and then returning the range. 基本上就像单击A6并在键盘上按ctrl+right Right,然后返回范围。

Note: If there are gaps in the range you won't get the correct result. 注意:如果范围内有差距,您将无法获得正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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