簡體   English   中英

Excel VBA根據下拉驗證列表選擇隱藏和取消隱藏列

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

我在單元格A1中有一個下拉驗證列表,其中包含類別項,例如“所有”,“在線商店”,“部門商店”,“專業商店”等等。 然后,從單元格B1到X1,除“全部”外,我具有前面提到的類別。

我想隱藏除下拉驗證列表中所選類別中的列以外的所有列。 另外,如果我在列表中選擇“全部”,則需要取消隱藏所有列。

我在Internet上找到了一個示例代碼,該代碼可以很好地隱藏未選擇的類別-但更改選擇時響應非常慢。 但是我無法使它與取消隱藏所有列的代碼一起使用。

相關代碼如下。 感謝您的反饋意見。

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

為了使您的代碼更快,請在循環之前關閉ScreenUpdating然后在循環之后重新打開

要添加“全部”功能,請使用下面的代碼


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更多詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM