Как скрыть или отобразить строки и столбцы с помощью свойства 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
Спасибо за внимание.
In this Article
- Select Entire Rows or Columns
- Select Single Row
- Select Single Column
- Select Multiple Rows or Columns
- Select ActiveCell Row or Column
- Select Rows and Columns on Other Worksheets
- Is Selecting Rows and Columns Necessary?
- Methods and Properties of Rows & Columns
- Delete Entire Rows or Columns
- Insert Rows or Columns
- Copy & Paste Entire Rows or Columns
- Hide / Unhide Rows and Columns
- Group / UnGroup Rows and Columns
- Set Row Height or Column Width
- Autofit Row Height / Column Width
- Rows and Columns on Other Worksheets or Workbooks
- Get Active Row or Column
This tutorial will demonstrate how to select and work with entire rows or columns in VBA.
First we will cover how to select entire rows and columns, then we will demonstrate how to manipulate rows and columns.
Select Entire Rows or Columns
Select Single Row
You can select an entire row with the Rows Object like this:
Rows(5).Select
Or you can use EntireRow along with the Range or Cells Objects:
Range("B5").EntireRow.Select
or
Cells(5,1).EntireRow.Select
You can also use the Range Object to refer specifically to a Row:
Range("5:5").Select
Select Single Column
Instead of the Rows Object, use the Columns Object to select columns. Here you can reference the column number 3:
Columns(3).Select
or letter “C”, surrounded by quotations:
Columns("C").Select
Instead of EntireRow, use EntireColumn along with the Range or Cells Objects to select entire columns:
Range("C5").EntireColumn.Select
or
Cells(5,3).EntireColumn.Select
You can also use the Range Object to refer specifically to a column:
Range("B:B").Select
Select Multiple Rows or Columns
Selecting multiple rows or columns works exactly the same when using EntireRow or EntireColumn:
Range("B5:D10").EntireRow.Select
or
Range("B5:B10").EntireColumn.Select
However, when you use the Rows or Columns Objects, you must enter the row numbers or column letters in quotations:
Rows("1:3").Select
or
Columns("B:C").Select
Select ActiveCell Row or Column
To select the ActiveCell Row or Column, you can use one of these lines of code:
ActiveCell.EntireRow.Select
or
ActiveCell.EntireColumn.Select
Select Rows and Columns on Other Worksheets
In order to select Rows or Columns on other worksheets, you must first select the worksheet.
Sheets("Sheet2").Select
Rows(3).Select
The same goes for when selecting rows or columns in other workbooks.
Workbooks("Book6.xlsm").Activate
Sheets("Sheet2").Select
Rows(3).Select
Note: You must Activate the desired workbook. Unlike the Sheets Object, the Workbook Object does not have a Select Method.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Is Selecting Rows and Columns Necessary?
However, it’s (almost?) never necessary to actually select Rows or Columns. You don’t need to select a Row or Column in order to interact with them. Instead, you can apply Methods or Properties directly to the Rows or Columns. The next several sections will demonstrate different Methods and Properties that can be applied.
You can use any method listed above to refer to Rows or Columns.
Methods and Properties of Rows & Columns
Delete Entire Rows or Columns
To delete rows or columns, use the Delete Method:
Rows("1:4").Delete
or:
Columns("A:D").Delete
VBA Programming | Code Generator does work for you!
Insert Rows or Columns
Use the Insert Method to insert rows or columns:
Rows("1:4").Insert
or:
Columns("A:D").Insert
Copy & Paste Entire Rows or Columns
Paste Into Existing Row or Column
When copying and pasting entire rows or columns you need to decide if you want to paste over an existing row / column or if you want to insert a new row / column to paste your data.
These first examples will copy and paste over an existing row or column:
Range("1:1").Copy Range("5:5")
or
Range("C:C").Copy Range("E:E")
Insert & Paste
These next examples will paste into a newly inserted row or column.
This will copy row 1 and insert it into row 5, shifting the existing rows down:
Range("1:1").Copy
Range("5:5").Insert
This will copy column C and insert it into column E, shifting the existing columns to the right:
Range("C:C").Copy
Range("E:E").Insert
Hide / Unhide Rows and Columns
To hide rows or columns set their Hidden Properties to True. Use False to hide the rows or columns:
'Hide Rows
Rows("2:3").EntireRow.Hidden = True
'Unhide Rows
Rows("2:3").EntireRow.Hidden = False
or
'Hide Columns
Columns("B:C").EntireColumn.Hidden = True
'Unhide Columns
Columns("B:C").EntireColumn.Hidden = False
Group / UnGroup Rows and Columns
If you want to Group rows (or columns) use code like this:
'Group Rows
Rows("3:5").Group
'Group Columns
Columns("C:D").Group
To remove the grouping use this code:
'Ungroup Rows
Rows("3:5").Ungroup
'Ungroup Columns
Columns("C:D").Ungroup
This will expand all “grouped” outline levels:
ActiveSheet.Outline.ShowLevels RowLevels:=8, ColumnLevels:=8
and this will collapse all outline levels:
ActiveSheet.Outline.ShowLevels RowLevels:=1, ColumnLevels:=1
Set Row Height or Column Width
To set the column width use this line of code:
Columns("A:E").ColumnWidth = 30
To set the row height use this line of code:
Rows("1:1").RowHeight = 30
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Autofit Row Height / Column Width
To Autofit a column:
Columns("A:B").Autofit
To Autofit a row:
Rows("1:2").Autofit
Rows and Columns on Other Worksheets or Workbooks
To interact with rows and columns on other worksheets, you must define the Sheets Object:
Sheets("Sheet2").Rows(3).Insert
Similarly, to interact with rows and columns in other workbooks, you must also define the Workbook Object:
Workbooks("book1.xlsm").Sheets("Sheet2").Rows(3).Insert
Get Active Row or Column
To get the active row or column, you can use the Row and Column Properties of the ActiveCell Object.
MsgBox ActiveCell.Row
or
MsgBox ActiveCell.Column
This also works with the Range Object:
MsgBox Range("B3").Column
Содержание
- Как скрыть или отобразить строки или столбцы в Excel с помощью VBA
- Похожие статьи
- Unhide All Rows / Columns
- Unhide All Rows
- Unhide All Columns
- Hide All Rows or Columns
- Macro to Unhide All Rows and Columns
- Macro to Unhide All Rows and Columns on all Sheets
- VBA Coding Made Easy
- VBA Code Examples Add-in
- Hide UnHide Rows in Excel Worksheet using VBA
- VBA Reference
- 120+ Project Management Templates
- Description:
- Hide UnHide Rows in Excel Worksheet using VBA – Solution(s):
- Hide-UnHide Rows in Excel Worksheet using VBA – Case study
- Hide-UnHide Rows in Excel Worksheet using VBA – Download Example File
- Hiding Rows based on a Condition
- Hide all rows with the text data /strings in Column A
- Hide all rows with the values as 0 in Column A
- Hide all rows with the negative values in Column A
- Hide all rows with the Positive values in Column A
- Hide all rows with the Even Number in Column A
- Hide all rows with the Odd Number in Column A
- Hide all rows if the value in Column A is greater than 50
- Hide all rows if the value in Column A is less than 100
- Hide / Unhide Columns & Rows
- Hide Columns or Rows
- Hide Columns
- Hide Rows
- Unhide Columns or Rows
- Unhide All Columns or Rows
- VBA Coding Made Easy
- VBA Code Examples Add-in
Как скрыть или отобразить строки или столбцы в Excel с помощью VBA
Довольно часто появляется необходимость в 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
Спасибо за внимание.
Похожие статьи
Что делать если условием таблицы является скрытие столбцов по условию: содержание в ячейках определенного значения? Нужен макрос? Можете помочь?
Например: Есть таблица со строками содержащими в заголовке название рыб (200 строк) и столбцами содержащими в заголовке название наживки для рыб(50 столбцов). В таблице есть диапазон содержащий в ячейках символ Х и символ Y. Используя стандартный фильтр выбираю в одном из столбцов «фильтровать по значению Х» Требуется: Выделив все ячейки оставшегося после фильтрации диапазона(например осталось только 20 строк названий рыб и все 50 столбцов названий наживки) скрыть СТОЛБЦЫ в которых ячейки диапазона не содержат хотя бы 1 символ Х (например в результате получиться 20 строк названий рыб и всего 5 СТОЛБЦОВ названий наживки)
Добрый день!
Выдает ошибку на многоточие и макрос не срабатывает 🙁 как быть в этой ситуации.
Пример 4: Скрытие нескольких столбцов в Excel
Sub HideCollumns()
Columns(«E:F»).Hidden = True
End Sub
Здравствуйте!
Подскажите, пжл, что делаю не так .
В примере №7, выдаёт ошибку 400, пишет:
«Method ‘Range’of object’_Worksheet’failed»
Подскажите, пожалуйста, как сделать, чтобы в примере №7, макрос ссылался бы НЕ на ИМЯ ячейки, а на ЗНАЧЕНИЕ, которое есть в ячейке ?
Иными словами, если ячейки А1, А2, А3 — содержать значение «хотим скрыть эти строки», то макрос скрывает эти строки (т.е. — строки 1, 2 и 3).
Если в какой-либо ячейке — иное значение, то, соответственно, эта строка НЕ скрывается.
Зараенее спасибо за ответ.
Попробуйте вот этот готовый макрос для скрытия и отражения строк по условию
https://yadi.sk/i/Hl2ePH5dbJ2bp
Спасибо за макрос!
Но адаптировать под себя — оказалось для меня слишком сложно ((.
Буду благодарен, если подскажите, как реализовать такую процедуру:
На ЗАЩИЩЁННОМ листе — две кнопки «Скрыть» и «Отобразить»
При нажатии кнопки «Скрыть» — происходит скрытие всех строк, одна из ячеек которых (скажем, все такие ячейки расположены в одном столбце «D») содержит значение «Счёт закрыт».
Лист при этом остаётся ЗАЩИЩЁННЫМ.
И, соответственно, при нажатии кнопки «Отобразить» — все скрытые строки — отображаются. Лист также остаётся защищённым.
Заранее спасибо !
А вот такой вопрос. Есть диапазон в 31 столбец, как скрыть столбцы выходящие за предел диапазона в зависимости от продолжительности месяца. то есть, если, к примеру февраль, то скрыть 3 или 2 последних столбца в диапазоне. Заранее спасибо за ответ !
Можно воспользоваться простеньким макрос скрытия столбцов по определенному условию (в данном случае, если в перовой строке есть цифра 1).
Источник
Unhide All Rows / Columns
In this Article
This tutorial will demonstrate how to unhide all rows and / or columns in an Excel worksheet using VBA.
Unhide All Rows
To unhide all rows in an Excel sheet, we will set the Hidden Property of all of the rows to FALSE.
We can access all rows by using the EntireRow Property of the Cells Object:
or by using the EntireRow Property of the Rows Object:
Unhide All Columns
Similarily, we can unhide all columns in an Excel sheet, by adjusting the Hidden Property of all the Columns.
You can access all of the columns by using the EntireColumn Property of the Cells Object:
or by using the EntireColumn Property of the Columns Object:
Hide All Rows or Columns
Of course, to hide all rows or columns, just set the Hidden Property to TRUE:
Macro to Unhide All Rows and Columns
Use this macro to unhide all rows and columns in a worksheet:
Macro to Unhide All Rows and Columns on all Sheets
This macro will unhide all rows and columns in all sheets in an Excel workbook:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Hide UnHide Rows in Excel Worksheet using VBA
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
50+ Excel Templates
50+ PowerPoint Templates
25+ Word Templates
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
Description:
We are required to Hide-UnHide the rows in some types of requirements. For examples we may have data for 3 different categories of items and we may want to show the respective items based on selection. In this case we can achieve by Hiding or Un-hiding the Rows. We will see this in the following examples:
Hide UnHide Rows in Excel Worksheet using VBA – Solution(s):
You can use EntireRow.Hidden property of Row. If you set hidden property TRUE, it will hide the rows. Or if you set it to FALSE then it will make rows to visible.
Hide-UnHide Rows in Excel Worksheet using VBA – An Example
The following example will show you how to Hide and Unhide the rows in excel worksheet using VBA. We can Hide or Unhide the multiple rows at a time. In this example I am hiding and Unhiding Rows 5 to 8.
Instructions:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Insert a Module for Insert Menu
- Copy the above code and Paste in the code window
- Save the file as macro enabled workbook
- Press F5 to run it
Output:
Here is the example screen-shot. You can download the file below and see the code. Hide button will call the procedure to hide the rows and unhide button will unhide the rows. For example, Food Button will show you the data and charts related to food. And ‘Show All’ button will show you all categories and ‘Hide All’ button will hide all categories.
Hide-UnHide Rows in Excel Worksheet using VBA – Case study
Here is the example case study. You can download the file below and see how its working. You can click on the buttons to view the respective data.
Hide-UnHide Rows in Excel Worksheet using VBA – Download Example File
You can download the example file and see the code for each button.
ANALYSISTABS – Hide-Unhide Rows
Hiding Rows based on a Condition
Let us assume we have 500 rows/records in a worksheet, we can loop through each row and check for a criteria and hide the rows. Let us see the verity of example with different criteria:
Hide all rows with the text data /strings in Column A
The following example will hide all all rows with the text data /strings in Column A.
Hide all rows with the values as 0 in Column A
The following example will hide all all rows with the values as 0 in Column A.
Hide all rows with the negative values in Column A
The following example will hide all all rows with the negative values in Column A.
Hide all rows with the Positive values in Column A
The following example will hide all all rows with the Positive values in Column A.
Hide all rows with the Even Number in Column A
The following example will hide all all rows with the Even Number in Column A.
Hide all rows with the Odd Number in Column A
The following example will hide all all rows with the Odd Number in Column A.
Hide all rows if the value in Column A is greater than 50
The following example will hide all all rows if the value in Column A is greater than 50.
Hide all rows if the value in Column A is less than 100
The following example will hide all all rows if the value in Column A is less than 100.
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Источник
Hide / Unhide Columns & Rows
In this Article
This tutorial will demonstrate how to hide and unhide rows and columns using VBA.
Hide Columns or Rows
To hide columns or rows set the Hidden Property of the Columns or Rows Objects to TRUE:
Hide Columns
There are several ways to refer to a column in VBA. First you can use the Columns Object:
or you can use the EntireColumn Property of the Range or Cells Objects:
Hide Rows
Similarly, you can use the Rows Object to refer to rows:
or you can use the EntireRow Property of the Range or Cells Objects:
Unhide Columns or Rows
To unhide columns or rows, simply set the Hidden Property to FALSE:
Unhide All Columns or Rows
To unhide all columns in a worksheet, use Columns or Cells to reference all columns:
Similarily to unhide all rows in a worksheet use Rows or Cells to reference all rows:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
When 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:
- 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?
- 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:
- 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.
- 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:
- It indicates whether the relevant row(s) or column(s) are hidden.
- 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:
- 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.
- 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:
- As Range objects. These objects can include, for example, (i) a single cell, (ii) an entire column, or (iii) an entire row.
- An address string.
- 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:
- The first syntax of the Worksheet.Range property (Worksheet.Range(Cell)).
- The range operator (:).
- 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:
- Is a read-only property. Therefore, you can use it to get its current setting.
- It returns a Range object.
- 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:
- Is read-only.
- It returns a Range object.
- 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:
- Worksheets(“Sheet1”).Range(“ColumnLetter:ColumnLetter”).EntireColumn: Returns the entire column whose letter you specify.
- Hidden = True: Sets the Hidden property to True.
This statement is composed of the following items:
- Worksheets(“Sheet1”): The Workbook.Worksheets property returns Sheet1 in the active workbook.
- Range(“ColumnLetter:ColumnLetter”): The Worksheet.Range property returns a range of cells composed of the column identified with ColumnLetter.
- EntireColumn: The Range.EntireColumn property returns the entire column you specify with ColumnLetter.
- 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
The following sample macro (Example_1_Hide_Column) uses the statement above:
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
The following macro example (Example_2_Hide_Contiguous_Columns) uses the sample statement above:
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:
- 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.
- 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”.
- 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
The following Sub procedure example (Example_3_Hide_NonContiguous_Columns) uses the statement above:
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:
- Worksheets(“Sheet1”).Range(“RowNumber:RowNumber”).EntireRow: Returns the entire row whose number you specify.
- 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
The following macro example (Example_4_Hide_Row) uses this statement:
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
The sample macro below (Example_5_Hide_Contiguous_Rows) uses the sample statement above:
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
The following sample Sub procedure (Example_6_Hide_NonContiguous_Rows) uses the statement above:
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:
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):
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:
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:
- Worksheets(“Sheet1”).Cells.EntireColumn: Returns all columns within Sheet1 of the active workbook.
- 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 the active workbook.
- Cells: The Worksheet.Cells property returns all the cells within the applicable worksheet.
- EntireColumn: The Range.EntireColumn property returns the entire column for all the columns in the worksheet.
- 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:
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:
- Worksheets(“Sheet1”).Columns.EntireColumn: Returns all the columns of Sheet1 of the active workbook.
- Hidden = False: Sets Range.Hidden to False.
The following are the main items within this statements:
- Worksheets(“Sheet1”): The Workbook.Worksheets property returns Sheet1 of the active workbook.
- Columns: The Worksheet.Columns property returns all the columns within the applicable worksheet.
- EntireColumn: The Range.EntireColumn property returns all entire columns within the worksheet.
- 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:
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:
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:
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:
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:
- Worksheets(“Sheet1”).Cells.EntireRow: Returns the all rows within Sheet1 in the active workbook.
- 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:
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:
- Worksheets(“Sheet1”).Rows.EntireRow: Returns all the rows in Sheet1 of the active workbook.
- Hidden = False: Sets the Hidden property to False.
The following are the main items within this statements:
- Worksheets(“Sheet1”): The Workbook.Worksheets property returns Sheet1 in the active workbook.
- Rows: The Worksheet.Rows property returns all the rows within the worksheet you’re working with.
- EntireRow: The Range.EntireRow property returns the entire row for all rows within the worksheet.
- 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:
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.
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Range.EntireRow property (Excel) |
vbaxl10.chm144123 |
vbaxl10.chm144123 |
excel |
Excel.Range.EntireRow |
9e66da51-6cef-4109-ea4e-2acaad42aa1f |
05/10/2019 |
medium |
Range.EntireRow property (Excel)
Returns a Range object that represents the entire row (or rows) that contains the specified range. Read-only.
Syntax
expression.EntireRow
expression A variable that represents a Range object.
Example
This example sets the value of the first cell in the row that contains the active cell. The example must be run from a worksheet.
ActiveCell.EntireRow.Cells(1, 1).Value = 5
This example sorts all the rows on a worksheet, including hidden rows.
Sub SortAll() 'Turn off screen updating, and define your variables. Application.ScreenUpdating = False Dim lngLastRow As Long, lngRow As Long Dim rngHidden As Range 'Determine the number of rows in your sheet, and add the header row to the hidden range variable. lngLastRow = Cells(Rows.Count, 1).End(xlUp).Row Set rngHidden = Rows(1) 'For each row in the list, if the row is hidden add that row to the hidden range variable. For lngRow = 1 To lngLastRow If Rows(lngRow).Hidden = True Then Set rngHidden = Union(rngHidden, Rows(lngRow)) End If Next lngRow 'Unhide everything in the hidden range variable. rngHidden.EntireRow.Hidden = False 'Perform the sort on all the data. Range("A1").CurrentRegion.Sort _ key1:=Range("A2"), _ order1:=xlAscending, _ header:=xlYes 'Re-hide the rows that were originally hidden, but unhide the header. rngHidden.EntireRow.Hidden = True Rows(1).Hidden = False 'Turn screen updating back on. Set rngHidden = Nothing Application.ScreenUpdating = True End Sub
[!includeSupport and feedback]
Hide UnHide Rows in Excel Worksheet using VBA
17 Comments
-
LS
July 24, 2015 at 10:23 AM — ReplyIn case I want to hide a row with condition…… for eg. I have a data base with some columns having text and some having numbers. If value in one of the columns becomes 0 or a negative number or a text then that row should get hidden.
could you please automate such a task in excel ?
thanks.
-
PNRao
July 25, 2015 at 3:04 AM — ReplyHi Lata,
I have updated the post with number of examples with criteria.
Please check now:Hiding Rows with Criteria in Excel Worksheet using VBA – Example File
Thanks-PNRao! -
Ben
August 7, 2015 at 8:00 PM — ReplyI tried to apply the same principle to columns with the conditions in row 1, but it can’t run.
Maybe someone knows what I need to fix in the script below :
Thanks!LastColumn = “EZ” ‘Let’s say I have columns until “EZ” in the report
For i = “A” To LastColumn ‘I want to loop through each column and check for required criteria‘to hide all the columns with the values as 0 in Row 1
If Range(1 & i) = 0 Then Column(i).EntireColumn.Hidden = TrueNext
-
PNRao
August 8, 2015 at 3:25 PM — Reply -
Ben
August 11, 2015 at 7:21 PM — ReplyAwesome!! Works like a charm,
Thanks again!
-
PNRao
August 11, 2015 at 11:51 PM — ReplyWelcome! I’m glad it worked. Thanks-PNRao
-
patrick
December 7, 2015 at 5:40 PM — ReplyMy desire is to specific cells. I have checkboxes and command buttons sprinkled throughout the worksheet. What I like to do is to hide the cells containing these form types. Maybe I have to redesign my worksheet to have all these buttons and boxes either all in a row or a column and hide the row/column. Have not had much luck with this. Can you help please?
-
amina1987
March 9, 2016 at 4:16 PM — Replygood morning.
thank you for this very usefull topic.for my work (for 2400 workbooks) i need to hide specific rows without openning the workbooks. is that possible? please help
-
Hey Valli,
This is my first attempt to actually write a Macro, and looks like I am stuck (Terribly Stuck)
Here is what I am trying to achieve:
I have a “Input” sheet which is linked (Via Vlookups in C:C) to 8-10 other worksheets (containing rates of materials). On a daily basis I have to insert the quantities (in Column D:D) next to the rates in the “Input” Sheet to multiply it with the corresponding rates to arrive at the total amount (in Column E:E) eventually.
The issue is I have to hide the materials (Entire Rows) I do not use in the Input sheet as well as the other reference sheets. Is there any way a macro can be written to help me? -
Guy
May 9, 2016 at 4:27 PM — ReplyHI PNRao,
Thanks for the great poste it really helped me, how would i loop this macro round to unhide the hidden rows when the box is unchecked?
Thanks
-
SANDIP DAVE
January 3, 2017 at 8:01 PM — ReplyI have a worksheet with live data of stock value, high, low in Column A3:A103, B3:B103, C3:C103 respectively and other formula in other columns and that updates every few seconds.
I would like to see only rows where below conditions is fulfilled and hide all other rows to filter out stocks.
Condition 1: =AND(A3=B3,A3>=L3,A3<=K3,A30)
Condition 2 =AND(A3=C3,A3>=S3,A3<=R3,A30)
Above condition is for example of Raw No.3 and which I am using for conditional formatting.
Kindly help to provide VBA codes for this. -
Skup
June 26, 2017 at 11:52 AM — ReplyGreetings,
How would someone show/hide rows in a 2nd range based upon the visibility of rows in a filtered range?
For example, if rows 5 through 20 are autofiltered by some criteria such that at a given state only rows 6, 8. 12. and 16 through 18 are visible, how could someone then show the matching rows in the range of rows from 105 through 120, so that along with rows 6, 8. 12. and 16 through 18 being visible by filtering; rows 106, 108, 112, 116, 117, and 118 are visible, while rows 105, 107, 109, 110, 11, 113, 114, 115, 119, and 120 are hidden?
How can this be triggered by the setting and resetting of the autofilter on the filtered range?
-
Orlando
March 21, 2019 at 8:18 AM — ReplyHow I can to hide Rows (A4:A6), and unhide Rows (A1:A3) in same time?
-
Carlos
February 4, 2020 at 8:42 PM — ReplyHi Everyone,
I need help to write a VB macro which allows me to use a Hide Rows/Unhide Rows button(s) using a zero value or blank range in Column D. I’ve tried taking various examples from here and other sites to try to help but either I’m doing something wrong (most likely) or the code wasn’t correct for my requirements in the first place!
Can anyone help please, I’m so lost!!!
-
Jasper
April 11, 2020 at 12:42 AM — ReplyIn your first example you say you’re hiding rows 5-8
IN the code you say Hide Rows 22-25
with the code set to 5:8Just got me confused
-
Eugene Van Loggerenberg
May 20, 2020 at 4:21 PM — ReplyGood day
I am just starting out and have zero VBA experience.
I have been able to create a button and link it to VBA and that part works.
Using the “Hide all rows with the values as 0 in Column A” I am having problems getting it to work.Assistance would be much appreciated.
Regards Eugene
-
PNRao
September 6, 2020 at 8:55 PM — Reply
Effectively Manage Your
Projects and Resources
ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.
We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.
Project Management
Excel VBA
Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.
Page load link
Go to Top
If you’re in the habit of hiding rows in Excel, you may also sometimes, have a need to unhide all rows in a worksheet in Excel.
In this tutorial, I will show you can quickly unhide all the rows in the worksheet with a simple VBA macro code.
Unhide Rows in a Worksheet in Excel Using VBA
Below is the VBA code that will instantly unhide all the rows in the entire worksheet;
Sub UnhideAllRows() Rows.EntireRow.Hidden = False End Sub
In case you want to unhide sheets in a specific range only (let’s say unhide all hidden rows in the first 20 rows only), you can use the below code:
Sub UnhideSpecificROws() For i = 1 To 20 Rows(i).Hidden = False Next i End Sub
The above uses the FOR NEXT loop to go through each row in the first 20 rows and then makes the hidden property FALSE, which is equivalent to making all rows visible.
Unhide Rows in All the Worksheets in Excel Using VBA
In case you want to unhide rows in all the worksheets at one go, you can do that as well.
Below is the VBA code that will go through each worksheet in the active workbook and then unhide all the rows in that worksheet:
Sub UnhideSpecificROws() For Each sh In Worksheets sh.Rows.EntireRow.Hidden = False Next sh End Sub
How to Use this VBA Code
To use this code, you need to add this to a module in the Visual Basic Editor in Excel, and then run this code from there.
Below are the steps to add this VBA code to unhide rows to a module in VB Editor:
- Right-click on any of the worksheet tabs
- Click on View Code. This will open the VB Editor window
- In the VB Editor, there would be a Project Explorer at the left of the window. If you don’t see it, go to the View option in the menu and then click on Project Explorer. This will make it appear.
- In the Project Explorer, right-click on any of the objects (sheet names or ThisWorkbook object)
- Go to the Insert option and then click on Module. This will insert a new Module in the Project Explorer
- Double Click on the Module to open its code window
- Copy and paste the above VBA code in that code window
Tip: The keyboard shortcut to open the VB Editor window in ALT + F11 (hold the ALT key and then press the F11 key)
Once you have the code in the module, you need to run this code to unhide rows in Excel.
Below are the steps to run the macro code from the VB Editor:
- Place the cursor anywhere in the code
- Press the F5 key (or click on the green play button in the toolbar)
Note: Since now the workbook has a VBA macro in it, you need to save it in the macro-enabled format (.XLSM). If you save it as a regular .XLSX file, the macro will not be saved
Adding the Macro to the Quick Access Toolbar
In case you have to unhide rows quite often, you can speed up the process by adding the VBA macro to the Quick Access toolbar. This way, when you have to unhide rows in Excel, you can simply click on the button and it will be done.
Below are the steps to add the macro to the Quick Access Toolbar:
- Click on the Customize Quick Access Toolbar (QAT) icon in the QAT
- Click on More Commands
- In the Excel Options dialog box, click on Macros from the drop-down. You will notice that your macro is listed in there
- Click on the macro that you want to add to the QAT
- Click on the ADD button
- Click OK
The above steps would add the macro to the Quick Access Toolbar.
Now, when you have to unhide rows in Excel, you can simply click on this macro icon and it would be done.
Note that since this macro is available only in the workbook where you have added it, you will not be able to use it in other workbooks. In case you want to access this from all the workbooks, you need to save it in the Personal Macro Workbook or create and add this as an add-in.
So this is how you can quickly use VBA to unhide rows in Excel.
All the methods I have shown here can also be used to unhide columns in Excel. You just need to modify the code to replace rows with columns.
Hope you found this tutorial useful.
You may also like the following Excel tutorials:
- How to Clear Contents in Excel without Deleting Formulas
- How to Select Every Other Cell in Excel (Or Every Nth Cell)
- How to Delete a Sheet in Excel Using VBA
- How to Copy Multiple Sheets to a New Workbook in Excel
- How to Select Alternate Columns in Excel (or every Nth Column)
- How to Filter as You Type in Excel (With and Without VBA)
- How to Hide Columns Based on Cell Value in Excel
- How to Delete Hidden Rows or Columns in Excel? 2 Easy Ways!
- How to Rearrange Rows In Excel