在工作中,我们常常遇到需要删除一个区域的所有空行的需求。如果只是百行的小数据,也许我们手动就可以完成,但现实往往我们面临上千条数据,如果是这样,手动就不再可以是可行的解决方法。我们期望用函数解决问题,但是excel的函数基本可以说是所有,都是基于单元格的计算,涉及到这样的增删行数的需求,便不能再使用函数。因此我们使用VBA来完成我们的需求。源代码来自MS的开发人员中心。原帖请查阅此处。
Sub Delete_Empty_Rows()
'The range from which to delete the rows.
' 定义一个选中的范围
Dim rnSelection As Range
'Row and count variables used in the deletion process.
Dim lnLastRow As Long
Dim lnRowCount As Long
Dim lnDeletedRows As Long
'Initialize the number of deleted rows.
' 初始删除的行为0
lnDeletedRows = 0
'Confirm that a range is selected, and that the range is contiguous.
' 判断是否选中一个连续区域
If TypeName(Selection) = "Range" Then
' 判断是否只选择了一个区域
If Selection.Areas.Count = 1 Then
'Initialize the range to what the user has selected,
'and initialize the count for the upcoming FOR loop.
' 将选择的范围赋值给刚才定义的range变量
Set rnSelection = Application.Selection
' 统计选中区域有多少行
lnLastRow = rnSelection.Rows.Count
'Start at the bottom row and work up: if the row is empty then
' 从最后一行开始,如果该行为空,则将该行删除
'delete the row and increment the deleted row count.
' 并且增加删除的行数
For lnRowCount = lnLastRow To 1 Step -1
' 如果countA统计出来为0,则说明该行为空行,于是删除
If Application.CountA(rnSelection.Rows(lnRowCount)) = 0 Then
rnSelection.Rows(lnRowCount).Delete
' 代表删除行数的变量增加
lnDeletedRows = lnDeletedRows + 1
End If
Next lnRowCount
' 调整所选择的区域,所有行数减去已删行数便为现存的行数,并且选择
rnSelection.Resize(lnLastRow - lnDeletedRows).Select
Else
' 选择多个区域的时候,会有如下的alert
MsgBox "Please select only one area.", vbInformation
End If
Else
' 选择不是range对象的元素,如图片等会有如下的alert
MsgBox "Please select a range.", vbInformation
End If
'Turn screen updating back on.
' 屏幕更新开启
Application.ScreenUpdating = True
End Sub
网友评论