excelvba

Hide columns using VBA in Excel 2010


Based on the value stored in a specific cell such as A1 of a worksheet I would like to hide a number of columns in the worksheet starting with column B.

Examples of what I am trying to do:

The difficulty is actually the way Excel (or least my Excel files) uses the alphabet (A, B, ...) for the name of the columns. I have done this on rows before using code like rows("2:" & range("A1").value) and set .hide = true


Solution

  • You can reference columns by their index number as such: Columns(indexnumber) and you can use Resize() to set the number of columns you want to select like so:

    Sub HideColumns()
        Dim numColumnsToHide
    
        numColumnsToHide = Cells(1, 1).Value
    
        Columns(2).Resize(, numColumnsToHide).Select
    
        Selection.EntireColumn.Hidden = True
    End Sub
    

    Obviously, this code doesn't have any validation of value in A1 so if someone runs HideColumns() without an integer in A1, bad things are going to happen. This also doesn't unhide any hidden columns.