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
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
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.
UnionOption 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