在不同的数据项之间插入空行

这是在Andrew Engwirda的博客中看到的代码,我将其摘录下来,并给出实例,供参考。
有时,我们需要在某列不同的数据项之间插入空行,使数据更清晰易懂。例如下图所示:

在A列中有一系列编号,有些相同有些不同,现在要求在不同的编号行之间插入空行,结果如下图所示:

此时,首先选中单元格区域A2:E7,然后运行下面的代码,即可得到所述结果:
Sub InsertRowsAtColumnDifferences()
    Dim lStartRow As Long
    Dim lLastRow As Long
    Dim lCounter As Long

    On Error Resume Next

    If ActiveWorkbook Is Nothing Then Exit Sub
    If TypeName(Selection) <> “Range” Then Exit Sub
    
    With Selection
        lStartRow = .Row
        lLastRow = lStartRow + .Columns(1).Cells.Count - 1
        For lCounter = lLastRow To lStartRow Step -1
            If Cells(lCounter, .Column).Value <> Cells(lCounter, .Column).Offset(1).Value Then
                If Cells(lCounter, .Column).Value <> “” And Cells(lCounter, .Column).Offset(1).Value <> “” Then
                    Cells(lCounter, .Column).Offset(1).EntireRow.Insert ‘insert rows
                End If
            End If
        Next lCounter
    End With
    On Error GoTo 0
End Sub

当有大量类似的数据需要整理时,该程序非常有用。
此外,还可以将代码:
Cells(lCounter, .Column).Offset(1).EntireRow.Insert
修改为代码:
.Rows(lCounter - lStartRow + 1).Borders(xlEdgeBottom).LineStyle = xlContinuous
则在某列不同的数据项之间加下边框线,如下图所示。

还可以将该处代码修改为代码:
ActiveSheet.HPageBreaks.Add Before:=Cells(lCounter, .Column).Offset(1)
将在不同的数据项之间进行分页。


提示:您可以在评论中使用HTML标签,且任何与HTML标签相同的符号都会被理解为HTML标签并以相应的格式显示.如果您的评论中有代码,可以使用相应的标签,例如,如果有VB或VBA代码,则可以使用[vb]标签,即[vb]放置的代码[/vb],这样会很清晰地显示代码.

1条评论

  1. 高绍伟 说到:

    其实用辅助列加排序功能也能实现,对于不会VBA的人来说更简单

留下回复