View and hide columns in excel using vba

后端 未结 2 617
悲哀的现实
悲哀的现实 2021-01-29 09:37

I have a worksheet with values in columns B:G. In the same sheet in cell A1 I have made a drop down list using data validation with values like A, B and C.

What I requir

2条回答
  •  滥情空心
    2021-01-29 10:30

    Try this:

    1. Open the VBA editor (ALT + F11)
    2. Double click Sheet1
    3. Select Worksheet in the top left drop down and Change in the top right hand drop down
    4. Paste this code

    NB- this assumes data validation is in cell A1

    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim allColumns As Range
    
        Set allColumns = Columns("B:G")
        allColumns.Hidden = True
    
        If Not Intersect(Target, Range("A1")) Is Nothing Then
            If Target.Value = "A" Then
                Columns("B:C").Hidden = False
            ElseIf Target.Value = "B" Then
                Columns("D:E").Hidden = False
            ElseIf Target.Value = "C" Then
                //Add more logic here
            End If
        End If
    End Sub
    

提交回复
热议问题