运行时错误 1004:按 VBA 的缩进级别对 Excel 列表进行分组

Runtime Error 1004: Group Excel list by indent level with VBA

我目前正在尝试修复 Excel VBA 宏。最终目标是按缩进级别对列表进行分组。

结构类似这样:

Row 1....Row2..Row3

Einheit-----A -40

Einheit------B -20

Einheit------C -20

Einheit------D 0

奇怪的是宏似乎一直工作到第 409 行。在第 410 行我得到 运行-time-error 1004。第 410 行的缩进级别是 9。也许你们有一个想法。

+++ 好的,所以我发现运行时错误在某种程度上与缩进级别一致。它总是出现在缩进级别 9 的行之后。 +++

Sub AutoGroupBOM()
    'Define Variables
    Dim StartCell As Range 'This defines the highest level of assembly, usually 1, and must be the top leftmost cell of concern for outlining, its our starting point for grouping'
    Dim StartRow As Integer 'This defines the starting row to beging grouping, based on the row we define from StartCell'
    Dim LevelCol As Integer 'This is the column that defines the assembly level we're basing our grouping on'
    Dim LastRow As Integer 'This is the last row in the sheet that contains information we're grouping'
    Dim CurrentLevel As Integer 'iterative counter'
    Dim i As Integer
    Dim j As Integer

    Application.ScreenUpdating = False 'Turns off screen updating while running.

    'Prompts user to select the starting row. It MUST be the highest level of assembly and also the top left cell of the range you want to group/outline"
    Set StartCell = Application.InputBox("Select top left cell for highest assembly level", Type:=8)
    StartRow = StartCell.Row
    LevelCol = StartCell.Column
    LastRow = ActiveSheet.UsedRange.Rows.Count

    'Remove any pre-existing outlining on worksheet, or you're gonna have 99 problems and an outline ain't 1
    Cells.ClearOutline

    'Walk down the bom lines and group items until you reach the end of populated cells in the assembly level column
    For i = StartRow To LastRow

        Rows(i).Select
        Level = Cells(i, LevelCol).IndentLevel
        For j = 1 To Level - 1
            Selection.Rows.Group
        Next j
    Next i

    Application.ScreenUpdating = True 'Turns on screen updating when done.

End Sub

提前致谢!

嘿,我发现问题出在哪里了。

最大值Excel 中的分组级别是 8,所以当我尝试第九次分组(缩进级别 9)时,我得到了 运行 时间错误!

Sub GroupByIndent()

    Dim rng As Range, cell As Range
    Dim i As Integer

    Set rng = Range("A6:A880")

    For Each cell In rng

        cell.Select

        For i = 1 To cell.IndentLevel

            Selection.Rows.Group

        Next

    Next cell

End Sub