Перейти к основному содержанию

Как использовать кнопку для отображения скрытых столбцов в Excel?

В этой статье будут показаны методы создания и использования кнопки для отображения и скрытия столбцов в Excel.

Используйте кнопку, чтобы показать скрытые столбцы с помощью кнопки переключения
Используйте кнопку, чтобы показать скрытые столбцы с помощью Kutools for Excel


Используйте кнопку, чтобы показать скрытые столбцы с помощью кнопки переключения

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

1. Нажмите Застройщик > Вставить > Кнопка переключения (элемент управления ActiveX). Смотрите скриншот:

Внимание: Если вы не видите Застройщик на ленте, нажмите показать / отобразить вкладку разработчика в Excel чтобы знать, как его включить.

2. Нарисуйте кнопку переключения на листе. Щелкните его правой кнопкой мыши и выберите Просмотреть код из контекстного меню. Смотрите скриншот:

3. В открывшемся Приложения Microsoft Visual Basic окна, замените все содержимое в окне кода приведенным ниже кодом VBA.

Код VBA: кнопка для отображения скрытых столбцов

Private Sub ToggleButton1_Click()
Dim xAddress As String
xAddress = "F:G"
If ToggleButton1.Value Then
    Application.ActiveSheet.Columns(xAddress).Hidden = True
Else
    Application.ActiveSheet.Columns(xAddress).Hidden = False
End If
End Sub

Внимание: «F: G» в коде означает, что столбцы F: G будут отображаться и скрываться во время выполнения кода. Пожалуйста, измените их под свои нужды.

4. Нажмите другой + Q клавиши одновременно, чтобы закрыть Приложения Microsoft Visual Basic окно.

5. Выключите Режим проектирования с щелчком Застройщик > Режим проектирования.

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

При повторном щелчке по нему отображаются столбцы.


Используйте кнопку, чтобы показать скрытые столбцы с помощью Kutools for Excel

Если на вашем листе уже есть скрытые столбцы, Kutools for ExcelАвтора Переключить, чтобы показать / скрыть все скрытые столбцы Утилита может помочь вам быстро показать и скрыть их одним щелчком мыши.

Перед применением Kutools for Excel, Пожалуйста, сначала скачайте и установите.

1. Нажмите Кутулс > Навигация.

2. Перейти к Список столбцов панель, а затем вы можете щелкнуть Переключить, чтобы показать / скрыть все скрытые столбцы кнопка, чтобы показать / скрыть столбцы на текущем листе.

  Если вы хотите получить бесплатную (30-дневную) пробную версию этой утилиты, пожалуйста, нажмите, чтобы загрузить это, а затем перейдите к применению операции в соответствии с указанными выше шагами.


Используйте кнопку, чтобы показать скрытые столбцы с помощью Kutools for Excel

Лучшие инструменты для офисной работы

🤖 Kutools AI Помощник: Революционный анализ данных на основе: Интеллектуальное исполнение   |  Генерировать код  |  Создание пользовательских формул  |  Анализ данных и создание диаграмм  |  Вызов функций Kutools...
Популярные опции: Найдите, выделите или определите дубликаты   |  Удалить пустые строки   |  Объедините столбцы или ячейки без потери данных   |   Раунд без формулы ...
Супер поиск: Множественный критерий VLookup    VLookup с несколькими значениями  |   VLookup по нескольким листам   |   Нечеткий поиск ....
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка   |  Зависимый раскрывающийся список   |  Выпадающий список с множественным выбором ....
Менеджер столбцов: Добавить определенное количество столбцов  |  Переместить столбцы  |  Переключить статус видимости скрытых столбцов  |  Сравнить диапазоны и столбцы ...
Рекомендуемые функции: Сетка Фокус   |  Просмотр дизайна   |   Большой Формулный Бар    Менеджер книг и листов   |  Библиотека ресурсов (Авто текст)   |  Выбор даты   |  Комбинировать листы   |  Шифровать/дешифровать ячейки    Отправлять электронные письма по списку   |  Суперфильтр   |   Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием...) ...
15 лучших наборов инструментов12 Текст Инструменты (Добавить текст, Удалить символы, ...)   |   50+ График Тип (Диаграмма Ганта, ...)   |   40+ Практических Формулы (Рассчитать возраст по дню рождения, ...)   |   19 Вносимые Инструменты (Вставить QR-код, Вставить изображение из пути, ...)   |   12 Конверсия Инструменты (Числа в слова, Конверсия валюты, ...)   |   7 Слияние и разделение Инструменты (Расширенные ряды комбинирования, Разделить клетки, ...)   |   ... и более

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

Описание


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (17)
Rated 5 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
Hello, I hope you are well.
If you can help me... I'd appreciate it. I would like to include an image in the button, would it be possible to place it directly in this code?
Rated 4 out of 5
This comment was minimized by the moderator on the site
Hi Eliza,

You can add a picture to a Toggle Button using its "Picture" property. Here's how to do it:
Right click the button and select Properties, in the Properties dialog box, go to the Categoried tab, look for the "Picture" property, click the ellipsis (...) next to the "Picture" property to open the file dialog and then you can select the picture you want.
This comment was minimized by the moderator on the site
Hi, Crystal
It doesn't work perfectly as I wanted, I had already tried... But I managed to do it another way. Thanks for the help! :)
Your content is very educational and helps many people, keep it up.
Rated 5 out of 5
This comment was minimized by the moderator on the site
Olá, espero que você esteja bem.
Se conseguir me ajudar.. agradeço. Gostaria de incluir uma imagem no botão, seria possível colocar diretamente nesse código?
This comment was minimized by the moderator on the site
Hi what is the code to hide rows instead of columns
Thanks
This comment was minimized by the moderator on the site
Hi Andy,
This VBA code can help. Please give it a try. Thank you.
You need to change the row number in the xAddress line to the rows you want to hide.
Private Sub ToggleButton1_Click()
'Updated by Extendoffice 20230915
Dim xAddress As String
xAddress = "5:10"
If ToggleButton1.Value Then
    Application.ActiveSheet.Rows(xAddress).Hidden = True
Else
    Application.ActiveSheet.Rows(xAddress).Hidden = False
End If
End Sub
This comment was minimized by the moderator on the site
Bonjour,

Top cela fonctionne bien !!

Cependant dans mon cas de figure je masque plusieurs groupes de colonnes ( ex : un bouton 1 pour masquer les colonnes D:E et un bouton 2 pour masquer les colonnes I:K). Comment faire pour que je puisse masquer un groupe de colonnes de façon indépendante et que je ne sois pas obligé d'activer le bouton 1 afin de pouvoir activer le bouton 2 ?

Je débute merci d'avance :)
This comment was minimized by the moderator on the site
Great written tutorial, but how do I create this button on a shared Excel sheet?
This comment was minimized by the moderator on the site
Hi Madison Taylor Delgado,
Are your workbooks shared on OneDrive or other applications? I am not able to solve this problem yet. Sorry for that.
This comment was minimized by the moderator on the site
Bom dia!

Eu gostaria de ajuda com um código para Control ActiveX onde eu pudesse selecionar colunas intercaladas.

Obrigado
This comment was minimized by the moderator on the site
I tried the formula on 3 buttons. The problem is they hide and unhide according to the sequenced they are inputted in the code. Is there anyway that I can click any button that will show/hide the columns not in sequence?
This comment was minimized by the moderator on the site
Adding to Ryan's comment, how about hiding a column based on the value of a cell? Basically making the xAdress an IF-function and not a predetermined range of columns.
This comment was minimized by the moderator on the site
Dear Liz,

Thank you for your comment!

VBA code in this tutorial can help you hiding specified columns based on the value of a cell. Please follow the below hyperlink to know more details.
https://www.extendoffice.com/documents/excel/2682-excel-hide-columns-based-on-dropdown-list.html
This comment was minimized by the moderator on the site
Hi there, How would you change it to select a bunch of non-adjacent cells?
This comment was minimized by the moderator on the site
Dear Ryan,

If you need to select a bunch of non-adjacent cells (every selected cell is interval of X cell) as below screenshot shown, please try the Select Interval Rows & Columns utility of Kutools for Excel.

You can also follow this link to know more about this feature. Thank you!
https://www.extendoffice.com/product/kutools-for-excel/excel-select-interval-rows-or-columns.html
This comment was minimized by the moderator on the site
Dear Ryan,

About the bunch of non-adjacent cells you need to select, can you provide a screenshot to show where they locating in your worksheet?
Thank you for your comment.
This comment was minimized by the moderator on the site
This was very helpful, thanks!
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations