2016-04-22 39 views
1

對不起,對於這個基本問題。刪除VBA中的所有數據,但只有一列

我想從工作表中刪除數據,但我實際上想要保留列A中的所有數據。我已經制定了如何清除所有行,同時保留標題但無法找到方法將數據保存在列A中。

有沒有人知道如何做到這一點?

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

回答

2

.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

2

另一種方式實現的是如下

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