删除VBA中的所有数据,但只有一列

问题描述:

对不起,对于这个基本问题。删除VBA中的所有数据,但只有一列

我想从工作表中删除数据,但我实际上想要保留列A中的所有数据。我已经制定了如何清除所有行,同时保留标题但无法找到方法将数据保存在列A中。

有没有人知道如何做到这一点?

With Worksheets("Data") 
    .Rows("2:" & .UsedRange.Count).Delete 
    End With 

.UsedRange.Count将返回使用范围内所有单元格的计数,而不仅仅是行。

如果我理解正确,您希望删除从B2到使用范围末尾的所有内容。你可以是这样做的:

With Worksheets("Data") 
    .Range("B2", Cells(.UsedRange.Rows.Count, .UsedRange.Columns.Count)).ClearContents 
End With 
+0

这个伟大的工程为OP,但不会在万一工作的UsedRange没有开始A1。 –

+0

@D_Bester,我的回答是针对这个问题,特别是为了展示如何使用'.UsedRange',而不是为了任何可能的想象。 – teylyn

另一种方式实现的是如下

Sub test() 
    lastrow = Cells.SpecialCells(xlCellTypeLastCell).Row 
    lastcolumn = Cells.SpecialCells(xlCellTypeLastCell).Column 
    Range("B2", Cells(lastrow, lastcolumn)).Delete 
End Sub