0

我正在尝试实现一个 VBA 代码,该代码隐藏所选过滤器的“不必要”列。

我正在使用切片器来简化表的过滤,但每个子集都有不同的信息(数据条目)。

例如。过滤类型 A 在 E 和 F 列中有数据,而 B 类型在 E 和 G 等中有数据。

现在我希望在任何给定时刻只显示其中包含数据的列,以使数据集更加用户友好。

我目前正在处理此代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim c As Long
    Dim n As Long
    Application.ScreenUpdating = False
    n = Rows(2).Find(What:="*", SearchDirection:=xlPrevious).Column
    For c = 3 To n
        Cells(3, c).EntireColumn.Hidden = (Application.CountA(Columns(c)) < 2)
    Next c
    Application.ScreenUpdating = True
End Sub

您可能会注意到,这不会从切片器中隐藏基于“活动过滤器”的列,也不会在更改过滤器时触发(例如,在切片器中选择 B 类而不是 A 类)

4

1 回答 1

0
Sub hideempty()
Dim i As Long
Dim LastCol As Long
Dim lastrow as long
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column 'If it has a fixed number of columns, _
                                                        you can replace this to LastCol = 5, for example. _
                                                        The number 1 is the row where the headers are
For i = 1 To LastCol
    lastrow = Cells(Rows.Count, i).End(xlUp).Row
    If lastrow <= 1 Then '1 considering every column has a header, regardless of having any data. _
                            If there are no headers, replace with 0
        Columns(i).EntireColumn.Hidden = True
    Else 'this will show columns that were previously hidden if now they have data
        Columns(i).EntireColumn.Hidden = False
    End If
Next i
End Sub
于 2017-08-21T10:50:03.897 回答