Group By With VBA

自古美人都是妖i 提交于 2019-12-23 05:30:38

问题


I have a worksheet that has a header row, and I want to group the rows using VBA. I have attempted this syntax

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

However, this will produce an error of:

Invalid or unqualified reference

Highlighting the line of code: After:=.Cells(1, 1)

What must I do to group all rows (sans the header) with VBA?

EDIT

Per comments, I edited my syntax to the below, which removes the error but this does not group all rows (excluding header). How should this be updated to group by the used range?

  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

回答1:


You don't need to use Select and Selection. Once you find the Range for rLastCell , you can read the last row property from your range with rLastCell.Row, and then just group them.

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

Note: you can get the last row that has data in Column A with :

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

(no need to use the .Find method)



来源:https://stackoverflow.com/questions/40677715/group-by-with-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!