目前,我正在使用以下内容从工作表中删除通常有200到700行的空白行。
Sub DeleteBlankRows2()
Dim i As Integer
Dim lastrow As Long
Dim Emptyrow As Long
lastrow = Application.CountA(Range("a:a"))
Emptyrow = Application.CountA(ActiveCell.EntireRow)
Range("a1").Select
For i = lastrow To 1 Step -1
If Emptyrow = 0 Then
Cells(i, 1).EntireRow.Delete
Else
Cells(i, 1).Offset(1, 0).Select
End If
Next i
End Sub
不幸的是,由于行数在每次运行时都会发生变化,因此出现了问题。我观察到的是第一个循环将删除四行,第二个循环删除两行,直到只剩下一行信息。不确定为什么删除包含A列中包含信息的单元格的行?
答案 0 :(得分:0)
创建一个范围对象,当您找到空行时,将该行添加到该范围。然后立即删除整个范围。
使用:
Sub DeleteBlankRows2()
Dim i As Integer
Dim rng As Range
Dim lastrow As Long
Dim Emptyrow As Long
With ActiveSheet 'better to use actual sheet name "WorkSheets("Sheet1")
lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
For i = lastrow To 1 Step -1
If Application.WorksheetFunction.CountA(.Rows(i)) = 0 Then
If rng Is Nothing Then
Set rng = .Rows(i)
Else
Set rng = Union(rng, .Rows(i))
End If
End If
Next i
If Not rng Is Nothing Then rng.Delete
End With
End Sub