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

Как сгруппировать и разгруппировать строки на защищенном листе?

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

Группировка и разгруппировка строк на защищенном листе с кодом VBA


стрелка синий правый пузырь Группировка и разгруппировка строк на защищенном листе с кодом VBA

Возможно, нет другого хорошего способа решить эту проблему, кроме использования кода VBA, сделайте следующее:

1. Активируйте свой рабочий лист, который вы хотите использовать, убедитесь, что рабочий лист еще не защищен.

2. Затем удерживайте ALT + F11 ключи, и он открывает Окно Microsoft Visual Basic для приложений.

3. Нажмите Вставить > Модулии вставьте следующий код в Окно модуля.

Код VBA: группировка и разгруппировка строк на защищенном листе

Sub EnableOutlining()
'Update 20140603
Dim xWs As Worksheet
Set xWs = Application.ActiveSheet
Dim xPws As String
xPws = Application.InputBox("Password:", xTitleId, "", Type:=2)
xWs.Protect Password:=xPws, Userinterfaceonly:=True
xWs.EnableOutlining = True
End Sub

4. Затем нажмите F5 нажмите клавишу для запуска этого кода, и появится диалоговое окно с напоминанием о вводе пароля для защиты текущего рабочего листа. Смотрите скриншот:

doc-группа-в-защищенном-листе1

5. Затем нажмите OK, ваш лист был защищен, но вы можете развернуть и сжать символы структуры на этом защищенном листе, см. снимок экрана:

doc-группа-в-защищенном-листе1

Внимание: Если ваш рабочий лист уже защищен, этот код не будет работать.

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

🤖 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 (33)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Fantástico, me resolveu rápido um grande problema, sua explicação é perfeita, didática, direta sem erros nem enrolação, parabéns. Obrigado!
This comment was minimized by the moderator on the site
Hello,
Thanks for these explanations, it works well.
I have a file with 3 outline symbols.
I would like to enable the user to group and ungroup rows when clicking on the symbols 1 and 2,but to prevent him from ungrouping rows when clicking on the symbol 3.
Is there any way to achieve this ?
Thanks in advance
This comment was minimized by the moderator on the site
这样筛选功能不能用啊
This comment was minimized by the moderator on the site
Is there a way to get this to work on a shared workbook? - I need the track changes, Thanks
This comment was minimized by the moderator on the site
f*ck, this stole my excel later and changed password privately
This comment was minimized by the moderator on the site
How To Group And Ungroup Rows and Columns In Protected Worksheet?
This comment was minimized by the moderator on the site
formidable
This comment was minimized by the moderator on the site
Someone might need this, I think I figured out how to make this work.

First, your code needs to be written in "ThisWorkbook" under Microsoft Excel Objects, as @peachyclean suggests.
Second, take the code that @Sravanthi wrote, and paste to the above mentioned location.

Sub Workbook_Open()
'Update 20140603
Dim xWs As Worksheet
Set xWs = Application.ActiveSheet
Dim xPws As String
xPws = "rfc" ''Application.InputBox("Password:", xTitleId, "", Type:=2)
xWs.Protect Password:=xPws, Userinterfaceonly:=True
xWs.EnableOutlining = True
End Sub

The thing is that you need to be on the sheet which you want to protect but allowing using grouping, and save the workbook and close, without protecting. Now if you open it, the macro starts automatically, it will make the sheet protected with the password "rfc". Now you can use the grouping, the sheet is protected.

For my solution, I've modified the password applied, so you can rewrite any password HERE:
xPws = "WRITEANYPASSWORDHERE" ''Application.InputBox("Password:", xTitleId, "", Type:=2)

Furthermore, I didn't want the to-be-protected sheet active when opening the file, therefore I've modified this part:
Set xWs = Application.ActiveSheet ->
Set xWs = Application.Worksheets("WRITEANYSHEET'SNAMEHERE")

Now it works like charm, sheet named 'WRITEANYSHEET'SNAMEHERE' is protected but the grouping applicable. On the long run, I think the problem will be that if I want to modify this file and keep the solution, I need to unprotect this sheet to make it work on the next opening. I guess you can write another macro to automatically unprotect when closing :)


I hope it helped.
This comment was minimized by the moderator on the site
This string looked to be exactly what I needed, as I know nothing about VBA. I was able to get this to work initially but as was pointed out, once you close the spreadsheet and reopen it, it no longer works. I tried to write the code in "ThisWorkbook" as noted but I can't figure out how to do that. I can see "ThisWorkbook" but I don't know how to write in it. Every way I see to create a module, it creates a new module in a the separate "Modules" folder, outside of the "Microsoft Excel Objects" folder. Any suggestions on how to put this code in "ThisWorkbook" ?
This comment was minimized by the moderator on the site
Hii.. this worked wonders. the only place where i am getting stuck now is that i need to do this for multiple sheets in the workbook. can u pls help with that.
This comment was minimized by the moderator on the site
do you have visuals for the VBA Code discussed 6 days ago to peachyclean about ThisWorkbook under Microsoft Objects instead of a new module. The functionality is lost when I go back into my workbook
This comment was minimized by the moderator on the site
To fix the issue of this not working in your file after you've closed it and opened it again, you have to paste the VBA code in "ThisWorkbook" under Microsoft Excel Objects instead of a new module. This will then automatically run the macro every time the file is opened.
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations