简体   繁体   English

Excel VBA根据下拉验证列表选择隐藏和取消隐藏列

[英]Excel VBA to hide and unhide columns based on a dropdown validation list selection

I have a dropdown validation list in cell A1 with category items like "All", "Online store", "Department store", "Specialized store" and so on. 我在单元格A1中有一个下拉验证列表,其中包含类别项,例如“所有”,“在线商店”,“部门商店”,“专业商店”等等。 Then, from cell B1 to X1 I have the before mentioned categories except "All". 然后,从单元格B1到X1,除“全部”外,我具有前面提到的类别。

I want to hide all columns except the ones from the category selected in the dropdown validation list. 我想隐藏除下拉验证列表中所选类别中的列以外的所有列。 Also I need to unhide all columns if I select "All" in the list. 另外,如果我在列表中选择“全部”,则需要取消隐藏所有列。

I found a sample code on the Internet which works fine to hide the non selected categories -but quite slow response when changing selection-. 我在Internet上找到了一个示例代码,该代码可以很好地隐藏未选择的类别-但更改选择时响应非常慢。 But I could not make it works together with a code to unhide all columns. 但是我无法使它与取消隐藏所有列的代码一起使用。

The related code is below. 相关代码如下。 Thanks for your feedback. 感谢您的反馈意见。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim R, V

If Target.Address = ("$A$1") Then
V = [A1].Value
For Each R In Range("B1:X1")
R.EntireColumn.Hidden = R.Value <> V
Next

End If

End Sub

To make your code faster turn off ScreenUpdating before looping and back on after 为了使您的代码更快,请在循环之前关闭ScreenUpdating然后在循环之后重新打开

To add the "All" functionality use the code bellow 要添加“全部”功能,请使用下面的代码


Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range) 'Target = cell being mdified (changed)

    Dim c As Variant, v As String

    If Target.Address = "$A$1" Then 'If edited cell is A1

        v = Target.Value2           '.Value2 = the text in the cell (without formatting)

        With Range("B1:X1")

            Application.ScreenUpdating = False

            .EntireColumn.Hidden = (v <> "All") 'Hides / Unhides all

            If v <> "All" Then  'If all are hidden, unhide the ones for criteria
                For Each c In .Cells
                    If c = v Then c.EntireColumn.Hidden = False
                Next
            End If

            Application.ScreenUpdating = True
        End With
    End If
End Sub

More details about .Value2 有关.Value2更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM