已回答此问题,但我需要一点帮助。我正在使用回答中提供的代码,但是我无法获得整个文档的子分组。这样的事情可能吗?自动分组Excel Excel VBA
Section Index
1 1
+ 1.1 2
++ 1.1.1 3
+++1.1.1.1 4
+++1.1.1.2 4
+++1.1.1.3 4
++ 1.1.2 3
++ 1.1.3 3
+ 1.2 2
+ 1.3 2
2 1
注:Plusses显示组。
我有这样的表,如上所述,我已经索引的章节与sublevels。我试图用excel组功能对这些部分进行分组,但是,我有超过3000行的数据,所以我试图自动化这个过程。我修改了我在这里找到的Excel VBA宏,并获得了下面的代码。
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 groupBegin, groupEnd As Integer
Dim i As Integer
Dim j As Integer
Dim n 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 levels' column top cell", Type:=8)
StartRow = StartCell.Row
LevelCol = StartCell.Column
LastRow = ActiveSheet.UsedRange.End(xlDown).Row 'empty rows above aren't included in UsedRange.rows.count => UsedRange.End
'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
groupBegin = StartRow + 1 'For the first group
For i = StartRow To LastRow
CurrentLevel = Cells(i, LevelCol)
groupBegin = i + 1
'Goes down until the entire subrange is selected according to the index
For n = i + 1 To LastRow
If Cells(i, LevelCol).Value = Cells(n, LevelCol).Value Then
If n - i = 1 Then
Exit For
Else
groupEnd = n - 1
Rows(groupBegin & ":" & groupEnd).Select
'If is here to prevent grouping level that have only one row
End If
Exit For
Else
End If
Next n
Next i
'For last group
Rows(groupBegin & ":" & LastRow).Select
Selection.Rows.Group
ActiveSheet.Outline.ShowLevels RowLevels:=1 'Minimize all the groups
ActiveSheet.Outline.SummaryRow = xlAbove 'Put "+" next to first line of each group instead of the bottom
Application.ScreenUpdating = True 'Turns on screen updating when done.
End Sub
基本上,我想在上面的代码做的是选择指数成分股和向下运行的细胞,直到该指数再次相同的值。基本上对于示例图表,我想选择行(2:4)并对它们进行分组。这不是代码实现的。而且,如果相邻行具有相同的索引,代码将跳过分组。
这是一个可行的方法,或者我应该重新考虑我的循环,以及如何?
我理解代码的逻辑,它似乎完美和对点,然而,我得到错误“对象未设置变量或块变量”为线“如果currRng.Value <> sRng.Value然后eRng = currRng“。另外,“如果没有(sRng)然后”我将此行更改为“IsEmpty(sRng)”,因为它不接受IsNothing的原因。 –
糟糕!回复:没什么 - 这是错误的关键字。我已将其更正为“如果sRng是Nothing”。和重新:对象变量错误,我忘记了'Set'关键字。在编辑之后,代码应该是正确的。这就是我提交未经测试的代码所获得的结果,对我感到羞耻。 – Vegard
这次我没有收到任何错误,但是,代码没有做任何事情。 –