【问题标题】:VBA Excel - Group rows based on specific criteriaVBA Excel - 根据特定条件对行进行分组
【发布时间】:2017-03-22 18:18:20
【问题描述】:

我对 VBA 非常陌生,我正在尝试在 Excel 中创建代码,该代码将根据范围内的值(例如 0)选择行,并使用 Excel 中的 group 函数将它们组合在一起。在下面的链接捕获中,您可以看到我从哪里开始(捕获 1)到我想去的地方(捕获 2)。

The following code is where I've got to which selects all rows which are 0. Unfortunately, I cannot use the Group function when multiple rows are selected that are not together.

我不太确定要在代码中添加什么以使其将第一组 0 分组,然后移动到下一组 0 并执行相同操作,直到到达范围的末尾。我还希望它跳过空白单元格,例如附加的屏幕截图第 13 行中的空白单元格。

Sub SelectGroupRows0()

Dim c As Range
Dim rng0 As Range
Dim block As Range

Set block = Range("B4:B23")

For Each c In block
    If c = 0 Then
        If rng0 Is Nothing Then Set rng0 = c.EntireRow
        Set rng0 = Union(rng0, c.EntireRow)

    Else: End If
Next c

rng0.Select
Selection.Rows.Group 

End Sub

对此的任何帮助将不胜感激。

提前致谢,

【问题讨论】:

  • 附带说明,如果顺序不重要,数据透视表可以更轻松地进行分组
  • 顺序很重要,因为这些表格用于 ThinkCell 瀑布图中。

标签: excel vba


【解决方案1】:

您有几个Else If 不在正确的位置。

另外,您需要循环遍历Union 范围Areas 以对它们中的每一个进行分组。

注意:您不需要使用rng0.Select 和更高版本的Selection.Rows.Group

代码

Option Explicit

Sub SelectGroupRows0()

Dim c As Range
Dim rng0 As Range
Dim block As Range

Set block = Range("B4:B23")

For Each c In block
    If Not IsEmpty(c) And c.Value = 0 Then
        If rng0 Is Nothing Then
            Set rng0 = c
        Else
            Set rng0 = Union(rng0, c)
        End If
    End If
Next c

' loop through your Range's Areas and group each one of them
For Each c In rng0.Areas
    c.EntireRow.Group
Next c

End Sub

【讨论】:

  • 这很好用。非常感谢 Shai Rado 提供的代码,我在某种程度上走在了正确的轨道上,但还有很长的路要走。欣赏!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 2021-08-29
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 2021-04-27
相关资源
最近更新 更多