View and hide columns in excel using vba

廉价感情. 提交于 2019-12-31 07:33:11

问题


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 require is when I select cell value A then columns B:C need to be visible and the other columns should be hidden from D:G. In the same way if I select B from the list I need to view columns D:E and B:C and F:G should be hidden.

Could you please help me on this.

Note: I don't have good knowledge in VBA.


回答1:


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



回答2:


Go to view --> macros.
Hit the dropdown and do "record new macro". Right click on a column header and do hide column.
Then do unhide column. Do Macros->stop recording. Macros-->View macros Click edit.

you get the following code:

Columns("C:C").Select
Selection.EntireColumn.Hidden = True
Selection.EntireColumn.Hidden = False

Now you know how to hide and show columns. First you select the column then your set Hidden = true or false.

Google: excel macro when cell value changes

Click the first link: http://support.microsoft.com/kb/213612

Take the code from that link and read the comments:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("A1:C10")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

        ' Display a message when one of the designated cells has been 
        ' changed.
        ' Place your code here.
        MsgBox "Cell " & Target.Address & " has changed."

    End If
End Sub

Make sure you read the link very closely. And follow the instructions. I find I sometimes rush and miss important details

Let me know if this is enough or you need more help.



来源:https://stackoverflow.com/questions/23844501/view-and-hide-columns-in-excel-using-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!