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

时间:2018-04-07 13:07:50

标签: excel-vba dropdown vba excel

我在单元格A1中有一个下拉列表验证列表,类别项目如" All"," Online store"," Department store"," Specialized商店"等等。然后,从单元格B1到X1我有前面提到的类别,除了" All"。

我想隐藏除下拉验证列表中所选类别之外的所有列。如果我选择" All"我还需要取消隐藏所有列。在列表中。

我在互联网上找到了一个示例代码,可以很好地隐藏未选择的类别 - 但在更改选择时响应非常慢。但我无法使其与代码一起取消隐藏所有列。

相关代码如下。感谢您的反馈。

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

1 个答案:

答案 0 :(得分:0)

要使代码更快,请在循环之前关闭ScreenUpdating,然后在

之后重新开启

添加&#34;全部&#34;功能使用下面的代码

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

有关.Value2

的更多详情