在 Excel 中删除空行的 6 种简单方法(一步步指导)

在 Excel 中删除空行的 6 种简单方法(一步步指导)

然后复制并将以下代码之一粘贴到新的空白模块中。

代码 1:从活动工作表中删除空行

Sub RemoveBlankRows()

'UpdatebyExtendoffice

Dim wsheet As Worksheet

Dim lastRow As Long

Dim i As Long

' Set the worksheet variable to the active sheet

Set wsheet = ActiveSheet

' Get the last row of data in the worksheet

lastRow = wsheet.Cells(wsheet.Rows.Count, 1).End(xlUp).Row

' Loop through each row in reverse order

For i = lastRow To 1 Step -1

' Check if the entire row is blank

If WorksheetFunction.CountA(wsheet.Rows(i)) = 0 Then

' If the row is blank, delete it

wsheet.Rows(i).Delete

End If

Next i

End Sub

代码 2:从选定区域中删除空行

Sub RemoveBlankRowsInRange()

'UpdatebyExtendoffice

Dim sRange As Range

Dim row As Range

' Prompt the user to select a range

On Error Resume Next

Set sRange = Application.InputBox(prompt:="Select a range", Title:="Kutools for Excel", Type:=8)

' Check if a range is selected

If Not sRange Is Nothing Then

' Loop through each row in reverse order

For Each row In sRange.Rows

' Check if the entire row is blank

If WorksheetFunction.CountA(row) = 0 Then

' If the row is blank, delete it

row.Delete

End If

Next row

Else

MsgBox "No range selected. Please select a range and run the macro again.", vbExclamation

End If

End Sub

相关推荐