如何使用VBA隐藏/取消隐藏"na"列



我有一行由31列组成(E27:AI27)。此范围内的所有单元格都从此范围之外的其他单元格获取输入(1-31 之间的数字),假设来自几个下拉列表。根据我如何调整这些下拉列表,该特定范围(E27:AI27)中的数字序列可能类似于以下替代项:

备选方案 01: 1 2 3 4 5..........................29 30 31 (共 31 个单元格)

替代 02: 2 3 4 5 6...........................29 30 31 na(共 31 个细胞)

备选方案03: 3 4 5 6 7...........................30 31 na (共31个细胞)

替代 04: 4 5 6 7 8......................30 31 纳纳 (共 31 个细胞)

等等。

备选案文30:30 31 纳娜娜

备选案文31:31娜娜

现在我想做的是自动暂时隐藏那些包含字符串"na"的列。当我再次重新调整我的下拉列表时,我希望能够取消隐藏那些从"na"变回数字的列。例如,我希望能够在备选方案 1 和备选方案 2 之间切换(见上文),改变我如何调整我的下拉列表。在这两种选择之间切换意味着 AI27 将从显示、隐藏、显示、隐藏等等(而E27AH27都会显示,因为它们里面都有数字,1-30。

最后但并非最不重要的一点是,有两个下拉列表可以控制单元格 E27:AI27 的值。下拉列表称为月份 (C18) 和下拉列表称为日期 (D18)。前者 (C18) 将天数设置为一个月。如果 C18=2 月,那么将有 28 天,最后两列 (AH:AI) 将是"na"。除此之外,后一个下拉列表 (D18) 设置开始日期,命名序列中的第一个数字(在单元格 E27 中)。如果 D18=21,那么二月月份的替代方案将是:

21 22 23 24 25 26 27 28 na(含 23 NA)

任何人都可以帮我为此设置 VBA 代码吗?

试试这个:

Private Sub Worksheet_Change(ByVal Target As Range)
    'change the "E23" with the cell with your dropdown
    If Not Intersect(Target, Range("E23")) Is Nothing Then
        Call UnhideHideColumns
    End If
End Sub
Sub UnhideHideColumns()
Dim bytColumnCheck As Byte
Dim blnNeedToUnhide As Boolean
Dim intFirstNAColumn As Integer
'check all columns and find out if they are already hidden
For bytColumnCheck = 5 To 35
    'if any of the columns is hidden, unhide all the columns to the right and exit loop
    If Cells(1, bytColumnCheck).EntireColumn.Hidden = True Then
        Range(Cells(1, bytColumnCheck), Cells(1, 35)).EntireColumn.Hidden = False
        Exit For
    End If
Next bytColumnCheck
'find first occurence of "na" in values, if any exists
If Not Cells.Find("na", LookIn:=xlValues, after:=Range("E27")) Is Nothing Then
    intFirstNAColumn = Cells.Find("na", LookIn:=xlValues).Column
    'now hide the columns to the right of the first "NA", including
    Range(Cells(1, intFirstNAColumn), Cells(1, 35)).EntireColumn.Hidden = True
End If
End Sub

请注意,每次带有下拉列表的单元格更改时都会调用Call UnhideHideColumns,即使假设从 Set1 更改为 Set1,或从 5 更改为 5。因此,它可以经常触发不必要的宏。

这对我有用:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim i As Integer
    For i = 9 To 40: Cells(28, i).EntireColumn.Hidden = Cells(28, i) = "na": Next
End Sub

最新更新