【问题标题】:How to Expand and Collapse Cells without Pivoting or Using Group Data Options如何在不旋转或使用组数据选项的情况下展开和折叠单元格
【发布时间】:2022-01-08 15:24:44
【问题描述】:

如何在没有数据透视表或组数据的情况下在excel中添加展开和折叠按钮,与附图相同?

expand and collapse button

【问题讨论】:

  • 该图片似乎是分组的行。为什么不想使用分组?
  • 不,这不是分组,分组按钮出现在标题的后面/上面(行号和列的字母)。这些是数据透视表按钮,如果文件中已经有分组,它们看起来会更简单且不那么混乱。
  • 尽管如此,你为什么不想使用分组呢?编写自己的隐藏/展开行函数需要做很多额外的工作。我假设您有特殊要求会影响这里的任何答案?
  • 正如我所说,这是为了使文件不那么混乱,已经有很多分组,我需要制作简短的可折叠和可展开列表。

标签: excel pivot-table grouping spreadsheet


【解决方案1】:

几年前,我为一位客户写过这样的文章。下面的代码演示了附加到按钮的宏,该按钮展开/折叠预定义的命名范围 ("pRngPurchaseOrders")。

这个范围有“保护行”,它们只是范围开始和结束处的空行,因此如果范围内有

' Expand or collapse the PurchaseOrder display region
Sub ExpandPurchaseOrders()
  Debug.Print Format(Now, "HH:mm:SS  "), "ExpandPurchaseOrders begin"
    ' get the PurchaseOrders range
    Dim nPurchaseOrders As Name, rPurchaseOrders As Range, lenPurchaseOrders As Long
    Set nPurchaseOrders = ws.Names("pRngPurchaseOrders")
    Set rPurchaseOrders = nPurchaseOrders.RefersToRange
    lenPurchaseOrders = rPurchaseOrders.Rows.Count
    
    ' if len=2 then assume we are expanding/expanded and updatePurchaseOrders
    ' if len > 2 and row(2) is invisible then we are collapsed, so expand and then updatePurchaseOrders
    ' if len > 2 and row(2) is visible then collapse
    
    If lenPurchaseOrders = 2 Then
        ' no rows, so we are expanding, but effectively already expanded
        PurchaseOrdersUpdate
        
    ElseIf lenPurchaseOrders > 2 Then
        Dim i As Long
        If rPurchaseOrders.Rows(2).Hidden = True Then
            'EXPAND: unhide all of the PurchaseOrder rows
            For i = 2 To lenPurchaseOrders - 1
                'first and last rows are hidden and used as anchors, so skip them
                rPurchaseOrders.Rows(i).Hidden = False
            Next i
            ' and update
            PurchaseOrdersUpdate
            
        Else
            'COLLAPSE: hide all of the PurchaseOrder rows
            For i = 2 To lenPurchaseOrders - 1
                'first and last rows are hidden and used as anchors, so skip them
                rPurchaseOrders.Rows(i).Hidden = True
            Next i
        
        End If
    
    End If
    
  Debug.Print Format(Now, "HH:mm:SS  "), "ExpandPurchaseOrders Done"
End Sub

为了使用它,我只是在工作表上创建了一个按钮,在命名范围旁边的文本中带有 "+",并将此宏分配给它。

【讨论】:

  • 好像很复杂,有没有其他办法?
猜你喜欢
  • 2013-06-07
  • 2019-04-23
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
  • 2019-12-29
相关资源
最近更新 更多