Excel VBA hide several columns in 1 line of code

Viewed 278

I want to hide several columns (that's not close to each other) in 1 line (shown below) in VBA but it doesn't work. What's wrong with it?

Columns("A, C:D").hidden = True
2 Answers

Use Range.EntireColumn.

Range("A:A,C:D").EntireColumn.Hidden = True

This thread is similar, and this answer demonstrates that Union is another option here as well.

Note that .EntireColumn is necessary; omitting it will throw a

Run-time error '1004':

Unable to set the Hidden property of the Range class.

Hide Columns Using Union

  • The best answer is already posted so here is kind of a cheating one: it is one line, but uses a function (with 'several' lines).
Option Explicit

Sub hideColumns()
    CombinedColumns(ActiveSheet, "A,C,H,K:M,O,R:U").Hidden = True
End Sub

Function CombinedColumns( _
    ByVal ws As Worksheet, _
    ByVal ColumnsList As String, _
    Optional ByVal Delimiter As String = ",") _
As Range
    Dim Cols() As String: Cols = Split(ColumnsList, Delimiter)
    Dim rg As Range
    Dim n As Long
    For n = 0 To UBound(Cols)
        If rg Is Nothing Then
            Set rg = ws.Columns(Cols(n))
        Else
            Set rg = Union(rg, ws.Columns(Cols(n)))
        End If
    Next n
    If Not rg Is Nothing Then
        Set CombinedColumns = rg.EntireColumn
    End If
End Function
Related