删除行完全除外第一

我正在使用Excel中的Visual Basic挣扎,以便除了前六行外,完全删除表中的所有行。 这里我举例说明与命令button相关的代码:

Dim i As Integer Dim tot_rows As Integer tot_rows = ThisWorkbook.Sheets("NAME").UsedRange.Rows.Count With Worksheets("NAME") For i = tot_rows To 6 Step -1 .Rows(i).ClearContents .Rows(i).EntireRow.Delete Next i 

当我执行代码时,它不会删除一行,你能告诉我为什么吗? tot_rows总是等于401(在表中,我可以看到401行,所以我认为这是正确的)。 可能超过401行,我不能直观地看到?

谢谢你的帮助,我很感激

使用范围可以是松鼠; 特别是当您的数据不在从第1行扩展的连续块中时。

 dim lr as long, lc as long with worksheets("sheet1") lr = .cells.Find(What:="*", After:=.Cells(1), LookIn:=xlFormulas, LookAt:=xlWhole, _ SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row lc = .cells.Find(What:="*", After:=.Cells(1), LookIn:=xlFormulas, LookAt:=xlWhole, _ SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).column .range(.cells(7, 1), .cells(lr, lc)).clear end with 

如果你是“删除”所有的行,那么你只需要清除它们作为一个块。 没有循环; 不删除。

对于所有的意图和目的,没有理由不这样做,你正在尝试。

 with worksheets("sheet1") .range(.cells(7, 1), .cells(.rows.count, .columns.count)).clear end with