分组依据 VBA
Group By With VBA
我有一个包含 header 行的工作表,我想使用 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
但是,这会产生以下错误:
Invalid or unqualified reference
突出显示代码行:After:=.Cells(1, 1)
我必须如何将所有行(没有 header)与 VBA 分组?
编辑
根据评论,我将语法编辑为以下内容,这消除了错误,但这并没有对所有行进行分组(不包括 header)。应该如何将其更新为按使用范围分组?
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
您不需要使用 Select
和 Selection
。找到 rLastCell
的范围后,您可以使用 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
方法)
我有一个包含 header 行的工作表,我想使用 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
但是,这会产生以下错误:
Invalid or unqualified reference
突出显示代码行:After:=.Cells(1, 1)
我必须如何将所有行(没有 header)与 VBA 分组?
编辑
根据评论,我将语法编辑为以下内容,这消除了错误,但这并没有对所有行进行分组(不包括 header)。应该如何将其更新为按使用范围分组?
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
您不需要使用 Select
和 Selection
。找到 rLastCell
的范围后,您可以使用 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
方法)