Excel vba макрос скрыть строки

Как скрыть или отобразить строки и столбцы с помощью свойства Range.Hidden из кода VBA Excel? Примеры скрытия и отображения строк и столбцов.

Range.Hidden — это свойство, которое задает или возвращает логическое значение, указывающее на то, скрыты строки (столбцы) или нет.

Синтаксис

Expression — выражение (переменная), возвращающее объект Range.

  • True — диапазон строк или столбцов скрыт;
  • False — диапазон строк или столбцов не скрыт.

Примечание

Указанный диапазон (Expression) должен охватывать весь столбец или строку. Это условие распространяется и на группы столбцов и строк.

Свойство Range.Hidden предназначено для чтения и записи.

Примеры кода с Range.Hidden

Пример 1

Варианты скрытия и отображения третьей, пятой и седьмой строк с помощью свойства Range.Hidden:

Sub Primer1()

‘Скрытие 3 строки

Rows(3).Hidden = True

‘Скрытие 5 строки

Range(«D5»).EntireRow.Hidden = True

‘Скрытие 7 строки

Cells(7, 250).EntireRow.Hidden = True

    MsgBox «3, 5 и 7 строки скрыты»

‘Отображение 3 строки

Range(«L3»).EntireRow.Hidden = False

‘Скрытие 5 строки

Cells(5, 250).EntireRow.Hidden = False

‘Скрытие 7 строки

Rows(7).Hidden = False

    MsgBox «3, 5 и 7 строки отображены»

End Sub

Пример 2

Варианты скрытия и отображения третьего, пятого и седьмого столбцов из кода VBA Excel:

Sub Primer2()

‘Скрытие 3 столбца

Columns(3).Hidden = True

‘Скрытие 5 столбца

Range(«E2»).EntireColumn.Hidden = True

‘Скрытие 7 столбца

Cells(25, 7).EntireColumn.Hidden = True

    MsgBox «3, 5 и 7 столбцы скрыты»

‘Отображение 3 столбца

Range(«C10»).EntireColumn.Hidden = False

‘Отображение 5 столбца

Cells(125, 5).EntireColumn.Hidden = False

‘Отображение 7 столбца

Columns(«G»).Hidden = False

    MsgBox «3, 5 и 7 столбцы отображены»

End Sub

Пример 3

Варианты скрытия и отображения сразу нескольких строк с помощью свойства Range.Hidden:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Sub Primer3()

‘Скрытие одновременно 2, 3 и 4 строк

Rows(«2:4»).Hidden = True

    MsgBox «2, 3 и 4 строки скрыты»

‘Скрытие одновременно 6, 7 и 8 строк

Range(«C6:D8»).EntireRow.Hidden = True

    MsgBox «6, 7 и 8 строки скрыты»

‘Отображение 2, 3 и 4 строк

Range(«D2:F4»).EntireRow.Hidden = False

    MsgBox «2, 3 и 4 строки отображены»

‘Отображение 6, 7 и 8 строк

Rows(«6:8»).Hidden = False

    MsgBox «6, 7 и 8 строки отображены»

End Sub

Пример 4

Варианты скрытия и отображения сразу нескольких столбцов из кода VBA Excel:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Sub Primer4()

‘Скрытие одновременно 2, 3 и 4 столбцов

Columns(«B:D»).Hidden = True

    MsgBox «2, 3 и 4 столбцы скрыты»

‘Скрытие одновременно 6, 7 и 8 столбцов

Range(«F3:H40»).EntireColumn.Hidden = True

    MsgBox «6, 7 и 8 столбцы скрыты»

‘Отображение 2, 3 и 4 столбцов

Range(«B6:D6»).EntireColumn.Hidden = False

    MsgBox «2, 3 и 4 столбцы отображены»

‘Отображение 6, 7 и 8 столбцов

Columns(«F:H»).Hidden = False

    MsgBox «6, 7 и 8 столбцы отображены»

End Sub


Довольно часто появляется необходимость в Excel скрывать или отображать строки или столбцы. Особенно это актуально, когда на листе размещается очень много информации и часть из них является вспомогательной и требуется не всегда и тем самым загромождает пространство, ухудшая восприятие.  Если это приходится делать часто, то делать это с помощью меню неудобно, особенно если приходится скрывать и отображать разные столбцы и строки.

Для существенного удобства можно написать простенький макрос, привязав его к кнопке и делать это  одним щелком мыши.

Вот так выглядят простые примеры, с помощью которых Вы без труда сможете скрывать или отображать строки и столбцы с помощью VBA

Пример 1: Скрыть строку 2 в Excel

Sub HideString()  ‘Это название макроса

Rows(2).Hidden = True

End Sub

Пример 2: Скрыть несколько строк в Excel (строку 3-5)

Sub HideStrings()

Rows(«3:5»).Hidden = True

End Sub

Пример 3: Скрыть столбец 2 в Excel

Sub HideCollumn()

Columns(2).Hidden = True

End Sub

Пример 4: Скрытие нескольких столбцов в Excel

Sub HideCollumns()

Columns(«E:F»).Hidden = True

End Sub

Пример 5: Скрытие строки по имени ячейки в Excel

Sub HideCell()

Range(«Возможности Excel»).EntireRow.Hidden = True

End Sub

Пример 6: Скрытие нескольких строк по адресам ячеек

Sub HideCell()

Range(«B3:D4»).EntireRow.Hidden = True

End Sub

Пример 7: Скрытие столбца по имени ячейки

Sub HideCell()

Range(«Возможности Excel»).EntireColumn.Hidden = True

End Sub

Пример 8: Скрытие нескольких столбцов по адресам ячеек

Sub HideCell()

Range(«C2:D5»).EntireColumn.Hidden = True

End Sub

Как видите процесс автоматического скрытия строк и столбцов очень прост, а применений данному приему огромное множество.

Для того, чтобы отобразить строки и  столбцы в Excel вы можете воспользоваться этими же макросами, но вместе True необходимо указать False

Например, макрос для того, чтобы отобразить строку 2 будет выглядеть следующим образом:

Sub ViewString()

Rows(2).Hidden = False

End Sub

Надеемся, что данная статья была полезна вам и ответила на вопрос: как скрыть или отобразить строки и столбцы в Excel с помощью VBA

Спасибо за внимание.

макрос удалит на листе все строки, в которых содержится искомый текст:

(пример — во вложении ConditionalRowsDeleting.xls)

Sub УдалениеСтрокПоУсловию()
    Dim ra As Range, delra As Range, ТекстДляПоиска As String
    Application.ScreenUpdating = False    ' отключаем обновление экрана

    ТекстДляПоиска = "Наименование ценности"    ' удаляем строки с таким текстом

    ' перебираем все строки в используемом диапазоне листа
    For Each ra In ActiveSheet.UsedRange.Rows
        ' если в строке найден искомый текст
        If Not ra.Find(ТекстДляПоиска, , xlValues, xlPart) Is Nothing Then
            ' добавляем строку в диапазон для удаления
            If delra Is Nothing Then Set delra = ra Else Set delra = Union(delra, ra)
        End If
    Next
    ' если подходящие строки найдены - удаляем их
    If Not delra Is Nothing Then delra.EntireRow.Delete
End Sub

Чтобы вместо удаления просто скрыть такие строки, замените строку

If Not delra Is Nothing Then delra.EntireRow.Delete

на

If Not delra Is Nothing Then delra.EntireRow.Hidden=TRUE

Расширенная версия этого макроса — с использованием UserForm для ввода искомого значения

Function ПоискСтрокПоУсловию(ByVal ТекстДляПоиска As String, Optional HideOnly As Boolean) As Long
    ' функция получает в качестве параметра ТекстДляПоиска (можно использовать символы * и ?)
    ' Если HideOnly = TRUE, то строки, содержащие в ячейках ТекстДляПоиска, скрываются,
    ' иначе (HideOnly = FALSE - по умолчанию) - удаляются
    ' Функция возвращает количество удалённых строк
    Dim ra As Range, delra As Range
    Application.ScreenUpdating = False    ' отключаем обновление экрана

    ' перебираем все строки в используемом диапазоне листа
    For Each ra In ActiveSheet.UsedRange.Rows
        ' если в строке найден искомый текст
        If Not ra.Find(ТекстДляПоиска, , xlValues, xlPart) Is Nothing Then
            ' добавляем строку в диапазон для удаления
            If delra Is Nothing Then Set delra = ra Else Set delra = Union(delra, ra)
        End If
    Next
    On Error Resume Next: ПоискСтрокПоУсловию = delra.Areas.Count ' количество найденных строк
    
    If Not delra Is Nothing Then    ' если подходящие строки найдены - скрываем или удаляем их
        If HideOnly Then delra.EntireRow.Hidden = True Else delra.EntireRow.Delete
    End If
End Function

Ещё один вариант кода, позволяющего выполнять поиск (с последующим удалением или скрытием строк) сразу по нескольким условиям:

Sub УдалениеСтрокПоНесколькимУсловиям()
    Dim ra As Range, delra As Range
    Application.ScreenUpdating = False    ' отключаем обновление экрана

    ' ищем и удаляем строки, содержащие заданный текст
    ' (можно указать сколько угодно значений, и использовать подстановочные знаки)
    УдалятьСтрокиСТекстом = Array("Наименование *", "Количество", _
                                  "текст?", "цен*сти", "*78*")
 
    ' перебираем все строки в используемом диапазоне листа
    For Each ra In ActiveSheet.UsedRange.Rows
        ' перебираем все фразы в массиве
        For Each word In УдалятьСтрокиСТекстом
            ' если в очередной строке листа найден искомый текст
            If Not ra.Find(word, , xlValues, xlPart) Is Nothing Then
                ' добавляем строку в диапазон для удаления
                If delra Is Nothing Then Set delra = ra Else Set delra = Union(delra, ra)
            End If
        Next word
    Next
 
    ' если подходящие строки найдены, то: (оставьте одну из 2 следующих строк)
    If Not delra Is Nothing Then delra.EntireRow.Hidden = True    ' скрываем их
    If Not delra Is Nothing Then delra.EntireRow.Delete    ' удаляем их
End Sub

Burk, Hugo121, Добрый день.

Я искала решение своей проблемы, увидела, что вы в макросах вроде разбираетесь, хотела бы спросить, если можно.

Я вообще в макросах не разбираюсь, но появилась необходимость использовать. Нужно было в очень большой таблице скрывать нужные месяцы. Вручную это занимает очень много времени так как повторение месяцев идет больше 100 раз.

Нашла в интернете макрос, что скрывал бы отмеченные столбцы :

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Sub Hide()
    Dim cell As Range
    Application.ScreenUpdating = False                              'отключаем обновление экрана для ускорения
    For Each cell In ActiveSheet.UsedRange.Rows(1).Cells            'проходим по всем ячейкам первой строки
        If cell.Value = "x" Then cell.EntireColumn.Hidden = True    'если в ячейке x - скрываем столбец
    Next
    For Each cell In ActiveSheet.UsedRange.Columns(1).Cells         'проходим по всем ячейкам первого столбца
        If cell.Value = "x" Then cell.EntireRow.Hidden = True       'если в ячейке x - скрываем строку
    Next
    Application.ScreenUpdating = True
End Sub
 
Sub Show()
    Columns.Hidden = False   'отменяем все скрытия строк и столбцов
    Rows.Hidden = False
End Sub

Но так как у меня условие это название месяца, я немного исправила, руководствуясь просто логикой:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Sub Hide()
    Dim cell As Range
    Application.ScreenUpdating = False
    For Each cell In ActiveSheet.UsedRange.Rows(1).Cells
        If cell.Value = "Январь" Then cell.EntireColumn.Hidden = True
        If cell.Value = "Февраль" Then cell.EntireColumn.Hidden = True
    Next
    Application.ScreenUpdating = True
End Sub
 
Sub Show()
    Columns.Hidden = False
    Rows.Hidden = False
End Sub

Теперь отображать месяца все он отображает, но нужное не скрывает.
Подскажите, пожалуйста, что я сделала не так?
Заранее спасибо!

Excel VBA tutorial about how to hide or unhide rows and columnsWhen working with Excel, you may find yourself in situations where you may need to hide or unhide certain rows or columns using VBA.

Consider, for example, the following situations (mentioned by Excel guru John Walkenbach in the Excel 2016 Bible) where knowing how to quickly and easily hide rows or columns with a macro can help you:

  • You’ve been working on a particular Excel workbook. However, before you send it by email to its final users, you want to hide certain information.
  • You want to print an Excel worksheet. However, you don’t want the print-out to include certain details or calculations.

Knowing how to do the opposite (unhide rows or columns using VBA) can also prove helpful in certain circumstances. A typical case where knowing how to unhide rows or columns with VBA can save you time is explained by Excel MVP Mike Alexander in Excel Macros for Dummies:

When you’re auditing a spreadsheet that you did not create, you often want to ensure that you’re getting a full view of the spreadsheet’s contents. To do so, all columns and rows must not be hidden.

Regardless of whether you want to hide or unhide cells or columns, I’m here to help you. In this tutorial, I provide an easy-to-follow introduction to the topic of using Excel VBA to hide or unhide rows or columns.

Further to the above, I provide 16 ready-to-use macro examples that you can use right now to hide or unhide rows and columns.

This Excel VBA Hide or Unhide Columns and Rows Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

The following table of contents lists the main sections of this blog post:

Let’s start by taking a look at the…

Excel VBA Constructs To Hide Rows Or Columns

If your purpose if to hide or unhide rows or columns using Excel VBA, you’ll need to know how to specify the following 2 aspects using Visual Basic for Applications:

  1. The cell range you want to hide or unhide.

    When you specify this range, you’re answering the question: Which are the rows or columns that Excel VBA should work with?

  2. Whether you want to (i) hide or (ii) unhide the range you specify in #1 above.

    The question you’re answering in this case is: Should Excel VBA hide or unhide the specified cells?

The following sections introduce some VBA constructs that you can use for purposes of specifying the 2 items above. More precisely:

  1. In the first part, I explain what VBA property you can use for purposes of specifying whether Excel VBA should (i) hide or (ii) unhide the cells its manipulating.
  2. In the second part, I introduce some VBA constructs you that you may find helpful for purposes of specifying the rows or columns you want to work with.

    For further information about the Range object, and how to create appropriate references, please refer to this thorough tutorial on the topic.

Hide Or Unhide With The Range.Hidden Property

In order to hide or unhide rows or columns, you generally use the Hidden property of the Range object.

The following are the main characteristics of the Range.Hidden property:

  1. It indicates whether the relevant row(s) or column(s) are hidden.
  2. It’s a read/write property. Therefore, you can both (i) fetch or (ii) modify its current setting.

The syntax of Range.Hidden is as follows:

expression.Hidden

“expression” represents a Range object. Therefore, throughout the rest of this VBA tutorial, I use the following simplified syntax:

Range.Hidden

The Range object you specify when working with the Hidden property is important because of the following:

  • If you’re modifying the property setting, this is the Range that you want to hide or unhide.
  • If you’re reading the property, this is the Range whose property setting you want to know.

When you specify the cell range you want to hide or unhide, specify the whole row or column. I explain how you can easily do this below.

How To Hide Rows Or Columns With The Range.Hidden Property

If you want to hide rows or columns, set the Hidden property to True.

The basic structure of the basic statement that you must use for these purposes is as follows:

Range.Hidden = True

How To Unhide Rows Or Columns With The Range.Hidden Property

If your objective is to unhide rows or columns, set the Range.Hidden property to False.

In this case, the basic structure of the relevant VBA statement is as follows:

Range.Hidden = False

Specify Row Or Column To Hide Or Unhide Using VBA

In order to be able to hide or unhide rows or columns, you need to have a good knowledge of how to specify which rows or columns Excel should hide or unhide.

In the following sections, I introduce several VBA properties that you can use for these purposes. These properties are commonly used for purposes of creating macros that hide or unhide rows or columns. Therefore, you’ll likely find them useful in many situations.

The following are the properties I explain below:

  • Worksheet.Range.
  • Worksheet.Cells.
  • Worksheet.Columns.
  • Worksheet.Rows.
  • Range.EntireRow.
  • Range.EntireColumn.

The last 2 properties (Range.EntireRow and Range.EntireColumn) are particularly important. As I mention above, when you hide a row or a column using the Range.Hidden property, you usually refer to the whole row or column. Range.EntireRow and Range.EntireColumn allow you to create such a reference. Therefore, you’ll be using these 2 properties often when creating macros that hide or unhide rows and columns.

The following descriptions are a relatively basic introduction to the topic of column and cell references in VBA.

Worksheet.Range Property

The main purpose of the Worksheet.Range property is to return a Range object representing either:

  • A single cell; or
  • A cell range.

The Worksheet.Range property has the following 2 syntax versions:

expression.Range(Cell)

expression.Range(Cell1, Cell2)

Which of the above versions you use depends on the characteristics of the Range object you want Visual Basic for Applications to return. Let’s take a closer look at them to understand how you can choose which one to use:

Syntax #1: expression.Range(Cell)

The first syntax version of Worksheet.Range is as follows:

expression.Range(Cell)

Within this statement, the relevant definitions are as follows:

  • expression: A Worksheet object.
  • Cell: A required parameter. It represents the range you want to work with.

In order to simplify the statement, I replace “expression” with “Worksheet” as follows:

Worksheet.Range(Cell)

The Cell parameter has the following main characteristics:

  1. As a general rule, Cell is a string specifying a cell range address or a named cell range. In this case, you generally specify Cell using A1-style references.
  2. You can use any of the following operators:

    Colon (:): The range operator. You can use colon (:) to refer to (i) entire rows, (ii) entire columns, (iii) ranges of contiguous cells, or (iv) ranges of non-contiguous cells.


    Space ( ): The intersection operator. You usually use space ( ) to refer to cells that are common to 2 separate ranges (their intersection).


    Comma (,): The union operator. You can use comma (,) to combine several ranges. You may find this particularly useful when working with ranges of non-contiguous rows or columns.

Syntax #2: expression.Range(Cell1, Cell2)

The second syntax version of the Worksheet.Range property is as follows:

expression.Range(Cell1, Cell2)

Some of the comments I make above regarding the first syntax version (expression.Range(Cell)) continue to apply. The following are the relevant items within this statement:

  • expression: A Worksheet object.
  • Cell1: The cell in the upper-left corner of the range you want to work with.
  • Cell2: The cell in the lower-right corner of the range.

Just as in the case of syntax #1 above, I simplify the statement as follows:

Worksheet.Range(Cell1, Cell2)

If you’re working with this version of the Range property, you can specify the parameters (Cell1 and Cell2) in the following ways:

  1. As Range objects. These objects can include, for example, (i) a single cell, (ii) an entire column, or (iii) an entire row.
  2. An address string.
  3. A range name.
How To Refer To An Entire Row Or Column With the Worksheet.Range Property

You can easily create a reference to an entire row or column using the following items:

  1. The first syntax of the Worksheet.Range property (Worksheet.Range(Cell)).
  2. The range operator (:).
  3. The relevant (i) row number(s), or (ii) column letter(s).

More precisely, you can refer to entire rows using a statement of the following form:

Worksheet.Range(“RowNumber1:RowNumber2”)

“RowNumber1” and “RowNumber2” are the number of the row(s) you’re referring to. If you’re referring to a single row, “RowNumber1” and “RowNumber2” are the same.

Similarly, you can create a reference to entire columns by using the following syntax:

Worksheet.Range(“ColumnLetter1:ColumnLetter2”)

“ColumnLetter1” and “ColumnLetter2” are the letters of the column you want to refer to. When you want to refer to a single column, “ColumnLetter1” and “ColumnLetter2” are the same.

Worksheet.Cells Property

The basic purpose of the Worksheet.Cells property is to return a Range object representing all the cells within a worksheet.

The basic syntax of Worksheet.Cells is as follows:

expression.Cells

“expression” represents a Worksheet object. Therefore, I simplify the syntax as follows:

Worksheet.Cells

In this blog post, I show how you can use the Cells property to return absolutely all of the cells within the relevant Excel worksheet. The basic structure of the statements you can use for these purposes is as follows:

Worksheet.Cells

This statement simply follows the basic syntax of the Worksheet.Cells property I introduce above.

Worksheet.Columns Property

The main purpose of the Worksheet.Columns property is to return a Range object representing all columns in a worksheet (the Columns collection).

The following is the basic syntax of Worksheet.Columns:

expression.Columns

“expression” represents a Worksheet object. Therefore, I simplify as follows:

Worksheet.Columns

Worksheet.Rows Property

The Worksheet.Rows property is materially similar to the Worksheet.Columns property I explain above. The main difference between Worksheet.Rows and Worksheet.Columns is as follows:

  • Worksheet.Columns works with columns
  • Worksheet.Rows works with rows.

Therefore, Worksheet.Rows returns a Range object representing all rows in a worksheet (the Rows collection).

The syntax of the Rows property is as follows:

expression.Rows

“expression” represents a Worksheet object. Considering this, I simplify the syntax as follows:

Worksheet.Rows

Range.EntireRow Property

The following are the main characteristics of the Range.EntireRow property:

  1. Is a read-only property. Therefore, you can use it to get its current setting.
  2. It returns a Range object.
  3. The Range object it returns represents the entire row(s) that contain the range you specify.

Let’s take a look at the syntax of Range.EntireRow to understand this better:

expression.EntireRow

“expression” represents a Range object. Therefore, I simplify the syntax as follows:

Range.EntireRow

As I explain in #3 above, the EntireRow property returns a Range object representing the entire row(s) containing the range you specify in the first item (Range) of this statement.

Range.EntireColumn Property

The Range.EntireColumn property is substantially similar to the Range.EntireRow property I explain above. The main difference is between EntireRow and EntireColumn is as follows:

  • EntireRow works with rows.
  • EntireColumn works with columns.

Therefore, the main characteristics of Range.EntireColumn are as follows:

  1. Is read-only.
  2. It returns a Range object.
  3. The returned Range object represents the entire column(s) containing the range you specify.

The syntax of Range.EntireColumn is substantially the same as that of Range.EntireRow:

expression.EntireColumn

Since “expression” represents a Range object, I can simplify this as follows:

Range.EntireColumn

Such a statement returns a Range object that represents the entire column(s) containing the range you specify in the first item (Range) of the statement.

Now, let’s take a look at some practical examples of VBA code that you can use to hide or unhide rows and columns. We start with…

All of the macro examples below work with a worksheet called “Sheet1” within the active workbook. The reference to this worksheet is built by using the Workbook.Worksheets property (Worksheets(“Sheet1”)).

In most situations, you’ll be working with a different worksheet or several worksheets. For these purposes, you can replace “Worksheets(“Sheet1″)” with the appropriate object reference.

VBA Code Example #1: Hide A Column

You can use a statement of the following form to hide one column:

Worksheets(“Sheet1”).Range(“ColumnLetter:ColumnLetter”).EntireColumn.Hidden = True

The statement proceeds roughly as follows:

  1. Worksheets(“Sheet1”).Range(“ColumnLetter:ColumnLetter”).EntireColumn: Returns the entire column whose letter you specify.
  2. Hidden = True: Sets the Hidden property to True.

This statement is composed of the following items:

  1. Worksheets(“Sheet1”): The Workbook.Worksheets property returns Sheet1 in the active workbook.
  2. Range(“ColumnLetter:ColumnLetter”): The Worksheet.Range property returns a range of cells composed of the column identified with ColumnLetter.
  3. EntireColumn: The Range.EntireColumn property returns the entire column you specify with ColumnLetter.
  4. Hidden = True: The Range.Hidden property is set to True.

    This property setting applies to the column returned by items #1 to #3 above. It results in Excel hiding that column.

The following statement is a practical example of how to hide a column. It hides column A (Range(“A:A”)).

Worksheets(“Sheet1”).Range(“A:A”).EntireColumn.Hidden = True

Excel worksheet with column A hidden

The following sample macro (Example_1_Hide_Column) uses the statement above:

Worksheets("Sheet1").Range("A:A").EntireColumn.Hidden = True

VBA Code Example #2: Hide Several Contiguous Columns

You can use the basic syntax that I introduce in the previous example #1 in order to hide several contiguous columns:

Worksheets(“Sheet1”).Range(“ColumnLetter1:ColumnLetter2”).EntireColumn.Hidden = True

For these purposes, you only need to make 1 change:

Instead of using a single column letter (ColumnLetter) as in the case above (column “A”), specify the following:

  • ColumnLetter1: Letter of the first column you want to hide.
  • ColumnLetter2: Letter corresponding to the last column you want to hide.

The following sample statement hides columns A to E (Range(“A:E”)):

Worksheets(“Sheet1”).Range(“A:E”).EntireColumn.Hidden = True

Excel worksheet with columns A to E hidden

The following macro example (Example_2_Hide_Contiguous_Columns) uses the sample statement above:

Worksheets("Sheet1").Range("A:E").EntireColumn.Hidden = True

VBA Code Example #3: Hide Several Non-Contiguous Columns

The previous 2 examples rely on the range operator (:) when using the Worksheet.Range property.

You can further extend these examples by using the union operator (,). More precisely, the union operator allows you to easily hide several non-contiguous columns.

The basic structure of the statement you can use for these purposes is as follows:

Worksheets(“Sheet1”).Range(“ColumnLetter1:ColumnLetter2,ColumnLetter3:ColumnLetter4,…,ColumnLetter#:ColumnLetter##”).EntireColumn.Hidden = True

Let’s take a closer look at the item that changes vs. the previous examples (Range(“ColumnLetter1:ColumnLetter2,ColumnLetter3:ColumnLetter4,…,ColumnLetter#:ColumnLetter##”)). For these purposes, the column letters you specify have the following meaning:

  • ColumnLetter1: Letter of first column of first contiguous column range you want to hide.
  • ColumnLetter2: Letter of last column of first contiguous range to hide.
  • ColumnLetter3: Letter of first column of second column range you’re hiding.
  • ColumnLetter4: Letter of last column of second contiguous range you want to hide.
  • ColumnLetter#: Letter of first column of last contiguous column range Excel should hide.
  • ColumnLetter##: Letter of last column within last column range VBA hides.

In other words, you specify the columns to hide in the following steps:

  1. Group all the columns you want to hide in groups of columns that are contiguous to each other.

    For example, if you want to hide columns A, B, C, D, E, G, H, I, L, M, N and O, group them as follows: (i) A to E, (ii) G to I, and (iii) L to O.

  2. Specify the first and last column of each of these groups of contiguous columns using the range operator (:). This is pretty much the same you do in the previous examples #1 and #2.

    In the example above, the 3 groups of contiguous columns become “A:E”, “G:I” and “L:O”.

  3. Separate each of these groups from the others by using the union operator (,).

    Continuing with the example above, the whole item becomes “A:E,G:I,L:O”.

The following sample VBA statement hides columns (i) A to E, (ii) G to I, and (iii) L to O:

Worksheets(“Sheet1”).Range(“A:E,G:I,L:O”).EntireColumn.Hidden = True

Excel worksheet with several hidden columns

The following Sub procedure example (Example_3_Hide_NonContiguous_Columns) uses the statement above:

Worksheets("Sheet1").Range("A:E,G:I,L:O").EntireColumn.Hidden = True

Excel VBA Code Examples To Hide Rows

The following 3 examples are substantially similar to those in the previous section (which hide columns). The main difference is that the following macros work with rows.

VBA Code Example #4: Hide A Row

A statement of the following form allows you to hide a single row:

Worksheets(“Sheet1”).Range(“RowNumber:RowNumber”).EntireRow.Hidden = True

The process followed by this statement is as follows:

  1. Worksheets(“Sheet1”).Range(“RowNumber:RowNumber”).EntireRow: Returns the entire row whose number you specify.
  2. Hidden = True: Sets the Range.Hidden property to True.

The statement is composed by the following items:

  • Worksheets(“Sheet1”): The Workbook.Worksheets property returns Sheet1 of the active workbook.
  • Range(“RowNumber:RowNumber”): The Worksheet.Range property returns a range of cells. This range is composed of the row identified with RowNumber.
  • EntireRow: The Range.EntireRow property returns the entire row specified by RowNumber.
  • Hidden = True: Sets the Hidden property to True.

    The property setting is applied to the row returned by items #1 to #3 above. The result is that Excel hides that particular row.

The following sample statement uses the syntax I describe above to hide row 1:

Worksheets(“Sheet1”).Range(“1:1”).EntireRow.Hidden = True

Excel worksheet with row 1 hidden

The following macro example (Example_4_Hide_Row) uses this statement:

Worksheets("Sheet1").Range("1:1").EntireRow.Hidden = True

VBA Code Example #5: Hide Several Contiguous Rows

You can easily extend the basic syntax that I introduce in the previous example #4 for purposes of hiding several contiguous rows:

Worksheets(“Sheet1”).Range(“RowNumber1:RowNumber2”).EntireRow.Hidden = True

The only difference between this statement and the one in example #4 above is the way in which you specify the row numbers (RowNumber1 and RowNumber2). More precisely:

  • In the previous example, you specify a single row number (RowNumber). This results in Excel hiding a single row.
  • In this case, you specify 2 row numbers (RowNumber1 and RowNumber2). Excel hides all the rows from (and including) RowNumber1 to (and including) RowNumber2.

Therefore, if you use the statement above, the relevant definitions are as follows:

  • RowNumber1: Number of first row you hide.
  • RowNumber2: Number of last row you hide.

The following example VBA statement hides rows 1 through 5 (Range(“1:5”)):

Worksheets(“Sheet1”).Range(“1:5”).EntireRow.Hidden = True

Worksheet with rows 1 to 5 hidden

The sample macro below (Example_5_Hide_Contiguous_Rows) uses the sample statement above:

Worksheets("Sheet1").Range("1:5").EntireRow.Hidden = True

VBA Code Example #6: Hide Several Non-Contiguous Rows

If you take the statements I provide in examples #4 and #5 above one step further by using the union operator (,), you can easily hide several non-contiguous rows.

In this case, the basic structure of the statement you can use is as follows:

Worksheets(“Sheet1”).Range(“RowNumber1:RowNumber2,RowNumber3:RowNumber4,…,RowNumber#:RowNumber##”).EntireRow.Hidden = True

The whole statement is pretty much the same as in the previous example. The items that change are the RowNumbers. When using this syntax, their meaning is as follows:

  • RowNumber1: Number of first row of first contiguous row range you’re hiding.
  • RowNumber2: Number of last row within first contiguous row range to hide.
  • RowNumber3: Number of first row within second contiguous row range you want to hide.
  • RowNumber4: Number of last row of second contiguous row range Excel hides.
  • RowNumber#: Number of first row of last contiguous row range to hide.
  • RowNumber##: Number of last row within last contiguous row range to be hidden with VBA.

The following example of VBA code hides rows (i) 1 to 5, (ii) 7 to 10, and (iii) 12 to 15:

Worksheets(“Sheet1”).Range(“1:5,7:10,12:15”).EntireRow.Hidden = True

Worksheet with several hidden rows

The following sample Sub procedure (Example_6_Hide_NonContiguous_Rows) uses the statement above:

Worksheets("Sheet1").Range("1:5,7:10,12:15").EntireRow.Hidden = True

Excel VBA Code Examples To Unhide Columns

The basic structure of the statements you use to hide or unhide a cell range is virtually the same. More precisely:

  • If you want to hide a cell range, the basic structure of the statement you use is as follows:

    Range.Hidden = True

  • If you want to unhide a cell range, the basic statement structure is as follows:

    Range.Hidden = False

The only thing that changes between these 2 statements is the setting of the Range.Hidden property. In order to hide the cell range, you set it to True. To unhide the cell range, you set it to False.

As a consequence of the above, several of the following statements to unhide columns are virtually the same as those I explain above to hide them.

Below, I show how you can unhide all columns in a worksheet. I don’t explain the structure of these macro examples above.

VBA Code Example #7: Unhide A Column

A statement of the following form allows you to unhide one column:

Worksheets(“Sheet1”).Range(“ColumnLetter:ColumnLetter”).EntireColumn.Hidden = False

This statement structure is virtually the same as that you can use to hide a column. The only difference is that, to unhide the column, you set the Range.Hidden property to False (Hidden = False).

When using this statement structure, “ColumnLetter” is the letter of the column you want to unhide.

The following sample VBA statement unhides column A (Range(“A:A”)):

Worksheets(“Sheet1”).Range(“A:A”).EntireColumn.Hidden = False

The following example macro (Example_7_Unhide_Column) contains the statement above:

Worksheets("Sheet1").Range("A:A").EntireColumn.Hidden = False

VBA Code Example #8: Unhide Several Contiguous Columns

You can use the following statement form to unhide several contiguous columns:

Worksheets(“Sheet1”).Range(“ColumnLetter1:ColumnLetter2”).EntireColumn.Hidden = True

This statement is substantially the same as the one you use to hide several contiguous columns. In order to unhide the columns (vs. hiding them), you set the Hidden property to False (Hidden = False).

When unhiding several contiguous columns, ColumnLetter1 and ColumnLetter2 represent the following:

  • ColumnLetter1: Letter of the first column to unhide.
  • ColumnLetter2: Letter of the last column you want to unhide.

The following practical example of a VBA statement unhides columns A to E (Range(“A:E”)):

Worksheets(“Sheet1”).Range(“A:E”).EntireColumn.Hidden = True

This statement appears in the sample macro below (Example_8_Unhide_Contiguous_Columns):

Worksheets("Sheet1").Range("A:E").EntireColumn.Hidden = False

VBA Code Example #9: Unhide Several Non-Contiguous Columns

A statement with the following structure allows you to unhide several non-contiguous columns:

Worksheets(“Sheet1”).Range(“ColumnLetter1:ColumnLetter2,ColumnLetter3:ColumnLetter4,…,ColumnLetter#:ColumnLetter##”).EntireColumn.Hidden = False

The statement is virtually the same to the one that you can use to hide several non-contiguous columns. To unhide the columns, this statement sets the Range.Hidden property to False (Hidden = False).

When specifying the letters of the columns to be unhidden, consider the following definitions:

  • ColumnLetter1: First column of first group of contiguous columns to unhide.
  • ColumnLetter2: Last column of first group of columns to unhide.
  • ColumnLetter3: First column of second group of contiguous columns that Excel unhides.
  • ColumnLetter4: Last column within second group of contiguous columns you want to unhide.
  • ColumnLetter#: First column within last group of contiguous columns that VBA unhides.
  • ColumnLetter##: Last column of last group of contiguous columns to unhide.

The following statement example unhides columns (i) A to E, (ii) G to I, and (iii) L to O:

Worksheets(“Sheet1”).Range(“A:E,G:I,L:O”).EntireColumn.Hidden = False

The following sample macro (Example_9_Unhide_NonContiguous_Columns) contains the statement above:

Worksheets("Sheet1").Range("A:E,G:I,L:O").EntireColumn.Hidden = False

VBA Code Examples #10 And #11: Unhide All Columns In A Worksheet

In some situations, you may want to ensure that all the columns in a worksheet are unhidden. The following VBA code examples help you do this:

VBA Code Example #10: Unhide All Columns In A Worksheet Using The Worksheet.Cells Property

The following statement works with the Worksheet.Cells property on the process of unhiding all the columns in a worksheet:

Worksheets(“Sheet1”).Cells.EntireColumn.Hidden = False

This VBA statement proceeds as follows:

  1. Worksheets(“Sheet1”).Cells.EntireColumn: Returns all columns within Sheet1 of the active workbook.
  2. Hidden = False: Sets the Hidden property to False.

The statement is composed of the following items:

  1. Worksheets(“Sheet1”): The Workbook.Worksheets property returns Sheet1 from the active workbook.
  2. Cells: The Worksheet.Cells property returns all the cells within the applicable worksheet.
  3. EntireColumn: The Range.EntireColumn property returns the entire column for all the columns in the worksheet.
  4. Hidden = False: The Range.Hidden property is set to False.

    This setting of the Hidden property applies to the columns returned by items #1 to #3 above. The final result is Excel unhiding all the columns in the worksheet.

The following macro example (Example_10_Unhide_All_Columns) unhides all columns in Sheet1 of the active workbook:

Worksheets("Sheet1").Cells.EntireColumn.Hidden = False

VBA Code Example #11: Unhide All Columns In A Worksheet Using The Worksheet.Columns Property

As an alternative to the previous code example #10, the following statement relies on the Worksheet.Columns property during the process of unhiding all the columns of the worksheet:

Worksheets(“Sheet1”).Columns.EntireColumn.Hidden = False

This statement proceeds in roughly the same way as that in the previous example:

  1. Worksheets(“Sheet1”).Columns.EntireColumn: Returns all the columns of Sheet1 of the active workbook.
  2. Hidden = False: Sets Range.Hidden to False.

The following are the main items within this statements:

  1. Worksheets(“Sheet1”): The Workbook.Worksheets property returns Sheet1 of the active workbook.
  2. Columns: The Worksheet.Columns property returns all the columns within the applicable worksheet.
  3. EntireColumn: The Range.EntireColumn property returns all entire columns within the worksheet.
  4. Hidden = False: The Hidden property is set to False.

    Since the Range.Hidden property applies to the columns returned by items #1 to #3 above, Excel unhides all the columns in the worksheet.

The following sample Sub procedure (Example_11_Unhide_All_Columns) unhides all the columns in Sheet1 of the active workbook:

Worksheets("Sheet1").Columns.EntireColumn.Hidden = False

Excel VBA Code Examples To Unhide Rows

As I explain above, the basic structure of the statements you use to hide or unhide a range of rows is virtually the same.

At a basic level, you only change the setting of the Range.Hidden property as follows:

  • To hide rows, you set Hidden to True (Range.Hidden = True).
  • To unhide rows, you set Hidden to False (Range.Hidden = False).

Therefore, several of the following sample VBA statements to unhide rows follow the same basic structure and logic as the ones above (which hide rows).

Below, I provide some (new) VBA code examples to unhide all rows in a worksheet.

VBA Code Example #12: Unhide A Row

The following statement structure allows you to unhide a row:

Worksheets(“Sheet1”).Range(“RowNumber:RowNumber”).EntireRow.Hidden = False

This structure follows the form and process I describe above for purposes of hiding a row. However, in this particular case, you set the Range.Hidden property to False (Hidden = False). This results in Excel unhiding the relevant row.

When you use this statement structure, “RowNumber” is the number of the row you want to unhide.

The following example of a VBA statement unhides row 1:

Worksheets(“Sheet1”).Range(“1:1”).EntireRow.Hidden = False

Check out the following sample macro (Example_12_Unhide_Row), which contains this statement:

Worksheets("Sheet1").Range("1:1").EntireRow.Hidden = False

VBA Code Example #13: Unhide Several Contiguous Rows

If you use the following statement structure, you can easily hide several contiguous rows:

Worksheets(“Sheet1”).Range(“RowNumber1:RowNumber2”).EntireRow.Hidden = False

This statement structure and logic is substantially the same as that I explain above for hiding contiguous rows. The only difference is the setting of the Range.Hidden property. In order to unhide the rows, you set it to False in the statement above (Hidden = False).

When you’re using the structure above, bear in mind the following definitions:

  • RowNumber1: Number of the first row you want to hide.
  • RowNumber2: Number of the last row Excel hides.

The following sample statement unhides rows 1 to 5 (Range(“1:5”)):

Worksheets(“Sheet1”).Range(“1:5”).EntireRow.Hidden = False

The macro example below (Example_13_Unhide_Contiguous_Rows) uses this statement:

Worksheets("Sheet1").Range("1:5").EntireRow.Hidden = False

VBA Code Example #14: Unhide Several Non-Contiguous Rows

You can use the following statement structure for purposes of unhiding several non-contiguous rows:

Worksheets(“Sheet1”).Range(“RowNumber1:RowNumber2,RowNumber3:RowNumber4,…,RowNumber#:RowNumber##”).EntireRow.Hidden = False

The statement structure is substantially the same as that you can use to hide several non-contiguous rows. For purposes of unhiding the rows, set the Hidden property to False (Hidden = False).

Further to the above, remember the following definitions:

  • RowNumber1: Number of first row of first row range to unhide.
  • RowNumber2: Number of last row of first row range you want to unhide.
  • RowNumber3: Number of first row within second range that Excel unhides.
  • RowNumber4: Number of last row of second contiguous row range you’re unhiding.
  • RowNumber#: Number of first row in last contiguous row range to unhide with VBA.
  • RowNumber##: Number of last row within last row range you want to unhide.

The following statement sample unhides rows (i) 1 to 5, (ii) 7 to 10, and (iii) 12 to 15:

Worksheets(“Sheet1”).Range(“1:5,7:10,12:15”).EntireRow.Hidden = False

You can check out the following macro example (Example_14_Unhide_Non_Contiguous_Rows), which uses this statement:

Worksheets("Sheet1").Range("1:5,7:10,12:15").EntireRow.Hidden = False

VBA Code Examples #15 And #16: Unhide All Columns In A Worksheet

If you want to unhide all the rows within a worksheet, you can use the following sample macros:

VBA Code Example #15: Unhide All Rows In A Worksheet Using The Worksheet.Cells Property

The following statement relies on the Worksheet.Cells property for purposes of unhiding all the rows in a worksheet:

Worksheets(“Sheet1”).Cells.EntireRow.Hidden = False

This VBA statement proceeds as follows:

  1. Worksheets(“Sheet1”).Cells.EntireRow: Returns the all rows within Sheet1 in the active workbook.
  2. Hidden = False: Sets the Hidden property to False.

The statement is composed of the following items:

  • Worksheets(“Sheet1”): The Workbook.Worksheets property returns Sheet1 from within the active workbook.
  • Cells: The Worksheet.Cells property returns all the cells within the relevant worksheet.
  • EntireRow: The Range.EntireRow property returns the entire row for all the rows in the worksheet.
  • Hidden = False: The Hidden property is set to False.

    This setting of the Range.Hidden property applies to the rows returned by items #1 to #3 above. The final result is Excel unhiding all the rows in the worksheet.

The following macro example (Example_15_Unhide_All_Rows) unhides all rows in Sheet1:

Worksheets("Sheet1").Cells.EntireRow.Hidden = False

VBA Code Example #16: Unhide All Rows In A Worksheet Using The Worksheet.Rows Property

The following VBA statement uses the Worksheet.Rows property when unhiding all the rows in a worksheet. You can use this as an alternative to the previous example #15:

Worksheets(“Sheet1”).Rows.EntireRow.Hidden = False

This statement proceeds in roughly the same way as that in the previous example:

  1. Worksheets(“Sheet1”).Rows.EntireRow: Returns all the rows in Sheet1 of the active workbook.
  2. Hidden = False: Sets the Hidden property to False.

The following are the main items within this statements:

  1. Worksheets(“Sheet1”): The Workbook.Worksheets property returns Sheet1 in the active workbook.
  2. Rows: The Worksheet.Rows property returns all the rows within the worksheet you’re working with.
  3. EntireRow: The Range.EntireRow property returns the entire row for all rows within the worksheet.
  4. Hidden = False: The Range.Hidden property is set to False.

    The Hidden property applies to the rows returned by items #1 to #3 above. Therefore, the statement results in Excel unhiding all the rows in the worksheet.

The sample macro that appears below (Example_16_Unhide_All_Rows) unhides all rows within Sheet1 by using the statement I explain above:

Worksheets("Sheet1").Rows.EntireRow.Hidden = False

Conclusion

After reading this Excel VBA tutorial you have enough knowledge to start creating macros that hide or unhide rows or columns.

More precisely, you’ve read about the following topics:

  • The Range.Hidden property, which you can use to indicate whether a row or column is hidden or unhidden.
  • How to use the following VBA properties for purposes of specifying the row(s) or column(s) you want to hide or unhide:
    • Worksheet.Range.
    • Worksheet.Cells.
    • Worksheet.Columns.
    • Worksheet.Rows.
    • Range.EntireRow.
    • Range.EntireColumn.

You also saw 16 macro examples to hide or unhide rows or columns that you can easily adjust and start using right now. The examples of VBA code I provide above can help you do any of the following:

  • Hide any of the following:
    • A column.
    • Several contiguous columns.
    • Several non-contiguous columns.
    • A row.
    • Several contiguous rows.
    • Several non-contiguous rows.
  • Unhide any of the following:
    • A column.
    • Several contiguous columns.
    • Several non-contiguous columns.
    • All the columns in a worksheet.
    • A row.
    • Several contiguous rows.
    • Several non-contiguous rows.
    • All the rows in a worksheet.

This Excel VBA Hide or Unhide Columns and Rows Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Books Referenced In This Excel VBA Tutorial

  • Alexander, Michael (2015). Excel Macros for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
  • Walkenbach, John (2015). Excel 2016 Bible. Indianapolis, IN: John Wiley & Sons Inc.

Понравилась статья? Поделить с друзьями:
  • Excel vba макрос при сохранении
  • Excel vba макрос при открытии листа
  • Excel vba макрос при изменении ячейки
  • Excel vba макрос при выборе листа
  • Excel vba макрос при активации листа