小组由与VBA

我有一个工作表,有一个标题行,我想用VBA分组行。 我尝试过这个语法

Sub GroupItTogether() Dim rLastCell As Range Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=.Cells(1, 1), _ LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False) Range("A2" & rLastCell).Select Selection.Rows.Group ActiveSheet.Outline.ShowLevels RowLevels:=1 End Sub 

但是,这会产生一个错误:

无效或不合格的参考

突出显示代码行: After:=.Cells(1, 1)

我必须做什么来组织所有的行(无头)与VBA?

编辑

每个评论,我编辑我的语法到下面,这将删除错误,但这不包括所有行(不包括头)。 应如何更新以使用范围进行分组?

  Sub GroupItTogether() Dim rLastCell As Range Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=Cells(1, 1), _ LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False) Range("A2" & rLastCell).Select Selection.Rows.Group ActiveSheet.Outline.ShowLevels RowLevels:=1 End Sub 

您不需要使用SelectSelection 。 一旦你find了rLastCell的Range,你可以使用rLastCell.Row从你的范围中读取最后一行属性,然后对它们进行分组。

 Option Explicit Sub GroupItTogether() Dim rLastCell As Range Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=Cells(1, 1), _ LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False) Range("A2:A" & rLastCell.Row).Rows.Group ActiveSheet.Outline.ShowLevels RowLevels:=1 End Sub 

注意 :你可以得到列A中具有数据的最后一行:

 lastrow = Cells(Rows.Count, "A").End(xlUp).Row 

(不需要使用.Find方法)