Защитить лист от изменений vba excel

Хитрости »

1 Май 2011              162419 просмотров


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

Иногда бывает полезно защитить данные на листе от изменений другими пользователями, но при этом так же надо будет работать с данными на листе из VBA(т.е. вносить изменения с помощью кода). Обычная защита листа, конечно, подходит, хоть и есть небольшой недостаток: надо перед каждым обращением к листу снимать с него защиту, выполнять необходимые действия и защищать заново:

Sub Write_in_ProtectSheet()
    'снимаем защиту с листа
    Worksheets("Лист1").Unprotect
    'если лист защищен с паролем 1234: Worksheets("Лист1").Unprotect "1234"
    'действия на листе.Например,изменение значения ячейки А1
    Cells("A1").Value = "www.excel-vba.ru"
    'устанавливаем защиту на лист
    Worksheets("Лист1").Protect
    'если лист был защищен с паролем 1234: Worksheets("Лист1").Protect "1234"
End Sub

Но есть метод проще.
Если выполнить ниже приведенную строчку кода, то пользователю невозможно будет изменить данные на листе(кроме тех, которые Вы сами разрешите), однако код VBA(макрос) сможет преспокойно вносить любые изменения, не снимая защиту.

Sub Protect_for_User_Non_for_VBA()
    ActiveSheet.Protect Password:="1111", UserInterfaceOnly:=True
End Sub

Основную роль здесь играет параметр UserInterfaceOnly. Если его установить в True, то это говорит Excel-ю, что коды VBA могут выполнять действия по изменению ячеек, не снимая защиты методом Unprotect. Однако сама защита листа при этом не снимается и вручную изменить данные ячеек, не сняв защиту с листа, невозможно.
Код выше устанавливает такую защиту только на активный лист книги. Но можно указать лист явно(например установить защиту на лист с именем Лист1 в активной книге и лист, идущий вторым по порядку в книге(Sheets(2))):

Sub Protect_for_User_Non_for_VBA()
    Sheets(2).Protect Password:="1111", UserInterfaceOnly:=True
    Sheets("Лист1").Protect Password:="1111", UserInterfaceOnly:=True
End Sub

Так же приведенный код можно еще чуть модернизировать и разрешить пользователю помимо изменения ячеек еще и использовать автофильтр:

Sub Protect_for_User_Non_for_VBA()
    Sheets(2).Protect Password:="1111", UserInterfaceOnly:=True
    'на лист "Лист1" поставим защиту и разрешим пользоваться фильтром
    Sheets("Лист1").Protect Password:="1111", AllowFiltering:=True, UserInterfaceOnly:=True
End Sub

Можно разрешить и другие действия(выделение незащищенных ячеек, выделение защищенных ячеек, форматирование ячеек, вставку строк, вставку столбцов и т.д. Чуть подробнее про доступные параметры можно узнать в статье Защита листов и ячеек в MS Excel). А как будет выглядеть строка кода с разрешенными параметрами можно узнать, записав макрорекордером установку защиты листа с нужными параметрами:

После этого получится строка вроде такой:

ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowInsertingColumns:=True, AllowInsertingRows:=True, AllowFiltering:=True

здесь я разрешил использовать автофильтр(AllowFiltering:=True), вставлять строки(AllowInsertingRows:=True) и столбцы(AllowInsertingColumns:=True).Чтобы добавить возможность изменять данные ячеек только через код VBA, останется добавить параметр UserInterfaceOnly:=True:

ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowInsertingColumns:=True, AllowInsertingRows:=True, AllowFiltering:=True, UserInterfaceOnly:=True

и так же неплохо бы добавить и пароль для снятия защиты, т.к. запись макрорекордером не записывает пароль:

ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowInsertingColumns:=True, AllowInsertingRows:=True, AllowFiltering:=True, UserInterfaceOnly:=True, Password:="1111"

Этот метод всем хорош, все отлично, но. Параметр UserInterfaceOnly сбрасывается сразу после закрытия книги. Т.е. если установить таким образом защиту на лист и закрыть книгу, то при следующем открытии защиты этой уже не будет — останется лишь стандартная защита. Поэтому, если необходимо такую защиту видеть постоянно, то данный макрос лучше всего прописывать на событие открытия книги(модуль ЭтаКнига(ThisWorkbook)).
Сделать это можно таким кодом:

Private Sub Workbook_Open()
    Sheets("Лист1").Protect Password:="1111", UserInterfaceOnly:=True
End Sub

Этот код сработает только после того, как книга будет открыта. А это значит, чтобы увидеть результат необходимо после записи этого кода в ЭтаКнига сохранить книгу, закрыть её и открыть заново. Тогда в сам момент открытия книги код сработает и установит на «Лист1» правильную защиту.

Часто так же бывает необходимо устанавливать одинаковую защиту на все листы книги. Сделать это можно таким кодом, который так же должен быть размещен в модуле ЭтаКнига(ThisWorkbook):

Private Sub Workbook_Open()
    Dim wsSh As Object
    For Each wsSh In Me.Sheets
        Protect_for_User_Non_for_VBA wsSh
    Next wsSh
End Sub
Sub Protect_for_User_Non_for_VBA(wsSh As Worksheet)
    wsSh.Protect Password:="1111", UserInterfaceOnly:=True
End Sub

Плюс во избежание ошибок лучше перед установкой защиты снимать ранее установленную(если она была):

Sub Protect_for_User_Non_for_VBA(wsSh As Worksheet)
    wsSh.Unrotect "1111"
    wsSh.Protect Password:="1111", UserInterfaceOnly:=True
End Sub

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

Private Sub Workbook_Open()
    Dim arr, sSh
    arr = Array("Отчет", "База", "Бланк")
    For Each sSh in arr
        Protect_for_User_Non_for_VBA Me.Sheets(sSh)
    Next
End Sub
Sub Protect_for_User_Non_for_VBA(wsSh As Worksheet)
    wsSh.Protect Password:="1111", AllowFiltering:=True, UserInterfaceOnly:=True
End Sub

Для применения в своих задачах в данном коде необходимо лишь изменить(добавить, удалить, вписать другие имена) имена листов в этой строке: Array(«Отчет», «База», «Бланк»)

Примечание: Метод защиты через UsefInterface всем хорош, но есть одно ограничение: метод невозможно использовать в книге с общим доступом(Рецензирование -Доступ к книге), т.к. при общем доступе существуют ограничения, среди которых и такое, которое запрещает изменять параметры защиты для книги в общем доступе.

Также см.:
Как разрешить изменять только выбранные ячейки?
Защита листов/снятие защиты
Как оставить возможность работать со структурой на защищенном листе?


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

Правильная защита макросом

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

Worksheets("Лист1").Unprotect Password:="123"
'тут макрос делает действия
Worksheets("Лист1").Protect Password:="123"

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

Есть гораздо более легкий и красивый способ решить задачу.

Нажмите Alt+F11, чтобы попасть в редактор Visual Basic. Затем найдите в левом верхнем углу в окне Project Explorer (если его не видно, то нажмите Ctrl+R) модуль ЭтаКнига (ThisWorkbook) и откройте двойным щелчком:

smart_protection1.gif

Скопируйте туда этот код:

Private Sub Workbook_Open()
    'включаем защиту первого листа для пользователя, но не макроса
    Worksheets("Лист1").Protect Password:="123", UserInterfaceOnly:=True
    
    'второй лист защищаем аналогично, но с возможностью пользоваться группировкой
    Worksheets("Лист2").EnableOutlining = True
    Worksheets("Лист2").Protect Password:="555", UserInterfaceOnly:=True
End Sub

Эта процедура будет автоматически запускаться при открытии файла и ставить защиту на заданные листы книги. Причем параметр UserInterfaceOnly, который мы дополнительно ввели, указывает Excel, что защита не должна распространяться на действия выполняемые макросом, а только на операции пользователя. Для второго листа все еще веселее — строка с параметром EnableOutlining разрешает пользоваться группировкой (символы плюс-минус для сворачивания-разворачивания строк и столбцов) на защищенном листе.

Всего три строчки кода, зато как удобно!

Ссылки по теме

  • Что такое макросы и куда копировать их код
  • Как поставить защиту листа, книги или всего файла

Protecting and unprotecting sheets is a common action for an Excel user. There is nothing worse than when somebody, who doesn’t know what they’re doing, overtypes essential formulas and cell values. It’s even worse when that person happens to be us; all it takes is one accidental keypress, and suddenly the entire worksheet is filled with errors. In this post, we explore using VBA to protect and unprotect sheets.

Protection is not foolproof but prevents accidental alteration by an unknowing user.

Sheet protection is particularly frustrating as it has to be applied one sheet at a time. If we only need to protect a single sheet, that’s fine. But if we have more than 5 sheets, it is going to take a while. This is why so many people turn to a VBA solution.

The VBA Code Snippets below show how to do most activities related to protecting and unprotecting sheets.

Download the example file: Click the link below to download the example file used for this post:

Adapting the code for your purposes

Unless stated otherwise, every example below is based on one specific worksheet. Each code includes Sheets(“Sheet1”)., this means the action will be applied to that specific sheet. For example, the following protects Sheet1.

Sheets("Sheet1").Protect

But there are lots of ways to reference sheets for protecting or unprotecting. Therefore we can change the syntax to use one of the methods shown below.

Using the active sheet

The active sheet is whichever sheet is currently being used within the Excel window.

ActiveSheet.Protect

Applying a sheet to a variable

If we want to apply protection to a sheet stored as a variable, we could use the following.

Dim ws As Worksheet

Set ws = Sheets("Sheet1")

ws.Protect

Later in the post, we look at code examples to loop through each sheet and apply protection quickly.

Let’s begin with some simple examples to protect and unprotect sheets in Excel.

Protect a sheet without a password

Sub ProtectSheet()

'Protect a worksheet
Sheets("Sheet1").Protect

End Sub

Unprotect a sheet (no password)

Sub UnProtectSheet()

'Unprotect a worksheet
Sheets("Sheet1").Unprotect

End Sub

Protecting and unprotecting with a password

Adding a password to give an extra layer of protection is easy enough with VBA. The password in these examples is hardcoded into the macro; this may not be the best for your scenario. It may be better to apply using a string variable, or capturing user passwords with an InputBox.

VBA Protect sheet with password

Sub ProtectSheetWithPassword()

'Protect worksheet with a password
Sheets("Sheet1").Protect Password:="myPassword"

End Sub

VBA Unprotect sheet with a password

Sub UnProtectSheetWithPassword()

'Unprotect a worksheet with a password
Sheets("Sheet1").Unprotect Password:="myPassword"

End Sub

NOTE – It is not necessary to unprotect, then re-protect a sheet to change the settings. Instead, just protect again with the new settings.

Using a password based on user input

Using a password that is included in the code may partly defeat the benefit of having a password. Therefore, the codes in this section provide examples of using VBA to protect and unprotect based on user input. In both scenarios, clicking Cancel is equivalent to entering no password.

Protect with a user-input password

Sub ProtectSheetWithPasswordFromUser()

'Protect worksheet with a password
Sheets("Sheet1").Protect Password:=InputBox("Enter a protection password:")

End Sub

Unprotect with a user-input password

Sub UnProtectSheetWithPasswordFromUser()

'Protect worksheet with a password
Sheets("Sheet1").Unprotect _
    Password:=InputBox("Enter a protection password:")

End Sub

Catching errors when incorrect password entered

If an incorrect password is provided, the following error message displays.

VBA to protect and unprotect sheets - Incorrect password

The code below catches the error and provides a custom message.

Sub CatchErrorForWrongPassword()

'Keep going even if error found
On Error Resume Next

'Apply the wrong password
Sheets("Sheet1").Unprotect Password:="incorrectPassword"

'Check if an error has occured
If Err.Number <> 0 Then
    MsgBox "The Password Provided is incorrect"
    Exit Sub
End If

'Reset to show normal error messages
On Error GoTo 0

End Sub

If you forget a password, don’t worry, the protection is easy to remove.

Applying protection to different parts of the worksheet

VBA provides the ability to protect 3 aspects of the worksheet:

  • Contents – what you see on the grid
  • Objects – the shapes and charts which are on the face of the grid
  • Scenarios – the scenarios contained in the What If Analysis section of the Ribbon

By default, the standard protect feature will apply all three types of protection at the same time. However, we can be specific about which elements of the worksheet are protected.

Protect contents

Sub ProtectSheetContents()

'Apply worksheet contents protection only
Sheets("Sheet1").Protect Password:="myPassword", _
    DrawingObjects:=False, _
    Contents:=True, _
    Scenarios:=False

End Sub

Protect objects

Sub ProtectSheetObjects()

'Apply worksheet objects protection only
Sheets("Sheet1").Protect Password:="myPassword", _
    DrawingObjects:=True, _
    Contents:=False, _
    Scenarios:=False

End Sub

Protect scenarios

Sub ProtectSheetScenarios()

'Apply worksheet scenario protection only
Sheets("Sheet1").Protect Password:="myPassword", _
    DrawingObjects:=False, _
    Contents:=False, _
    Scenarios:=True

End Sub

Protect contents, objects and scenarios

Sub ProtectSheetAll()

'Apply worksheet protection to contents, objects and scenarios
Sheets("Sheet1").Protect Password:="myPassword", _
    DrawingObjects:=True, _
    Contents:=True, _
    Scenarios:=True

End Sub

Applying protection to multiple sheets

As we have seen, protection is applied one sheet at a time. Therefore, looping is an excellent way to apply settings to a lot of sheets quickly. The examples in this section don’t just apply to Sheet1, as the previous examples have, but include all worksheets or all selected worksheets.

Protect all worksheets in the active workbook

Sub ProtectAllWorksheets()

'Create a variable to hold worksheets
Dim ws As Worksheet

'Loop through each worksheet in the active workbook
For Each ws In ActiveWorkbook.Worksheets

    'Protect each worksheet
    ws.Protect Password:="myPassword"

Next ws

End Sub

Protect the selected sheets in the active workbook

Sub ProtectSelectedWorksheets()

Dim ws As Worksheet
Dim sheetArray As Variant

'Capture the selected sheets
Set sheetArray = ActiveWindow.SelectedSheets

'Loop through each worksheet in the active workbook
For Each ws In sheetArray

    On Error Resume Next

    'Select the worksheet
    ws.Select

    'Protect each worksheet
    ws.Protect Password:="myPassword"

    On Error GoTo 0

Next ws

sheetArray.Select

End Sub

Unprotect all sheets in active workbook

Sub UnprotectAllWorksheets()

'Create a variable to hold worksheets
Dim ws As Worksheet

'Loop through each worksheet in the active workbook
For Each ws In ActiveWorkbook.Worksheets

'Unprotect each worksheet
ws.Unprotect Password:="myPassword"

Next ws

End Sub

Checking if a worksheet is protected

The codes in this section check if each type of protection has been applied.

Check if Sheet contents is protected

Sub CheckIfSheetContentsProtected()

'Check if worksheets contents is protected
If Sheets("Sheet1").ProtectContents Then MsgBox "Protected Contents"

End Sub

Check if Sheet objects are protected

Sub CheckIfSheetObjectsProtected()

'Check if worksheet objects are protected
If Sheets("Sheet1").ProtectDrawingObjects Then MsgBox "Protected Objects"

End Sub

Check if Sheet scenarios are protected

Sub CheckIfSheetScenariosProtected()

'Check if worksheet scenarios are protected
If Sheets("Sheet1").ProtectScenarios Then MsgBox "Protected Scenarios"

End Sub

Changing the locked or unlocked status of cells, objects and scenarios

When a sheet is protected, unlocked items can still be edited. The following codes demonstrate how to lock and unlock ranges, cells, charts, shapes and scenarios.

When the sheet is unprotected, the lock setting has no impact. Each object becomes locked on protection.

All the examples in this section set each object/item to lock when protected. To set as unlocked, change the value to False.

Lock a cell

Sub LockACell()

'Changing the options to lock or unlock cells
Sheets("Sheet1").Range("A1").Locked = True

End Sub

Lock all cells

Sub LockAllCells()

'Changing the options to lock or unlock cells all cells
Sheets("Sheet1").Cells.Locked = True

End Sub

Lock a chart

Sub LockAChart()

'Changing the options to lock or unlock charts
Sheets("Sheet1").ChartObjects("Chart 1").Locked = True

End Sub

Lock a shape

Sub LockAShape()

'Changing the option to lock or unlock shapes
Sheets("Sheet1").Shapes("Rectangle 1").Locked = True

End Sub

Lock a Scenario

Sub LockAScenario()

'Changing the option to lock or unlock a scenario
Sheets("Sheet1").Scenarios("scenarioName").Locked = True

End Sub

Allowing actions to be performed even when protected

Even when protected, we can allow specific operations, such as inserting rows, formatting cells, sorting, etc. These are the same options as found when manually protecting the sheet.

Standard protection settings

Allow sheet actions when protected

Sub AllowSheetActionsWhenProtected()

'Allowing certain actions even if the worksheet is protected
Sheets("Sheet1").Protect Password:="myPassword", _
    DrawingObjects:=False, _
    Contents:=True, _
    Scenarios:=False, _
    AllowFormattingCells:=True, _
    AllowFormattingColumns:=True, _
    AllowFormattingRows:=True, _
    AllowInsertingColumns:=False, _
    AllowInsertingRows:=False, _
    AllowInsertingHyperlinks:=False, _
    AllowDeletingColumns:=True, _
    AllowDeletingRows:=True, _
    AllowSorting:=False, _
    AllowFiltering:=False, _
    AllowUsingPivotTables:=False

End Sub

Allow selection of any cells

Sub AllowSelectionAnyCells()

'Allowing selection of locked or unlocked cells
Sheets("Sheet1").EnableSelection = xlNoRestrictions

End Sub

Allow selection of unlocked cells

Sub AllowSelectionUnlockedCells()

'Allowing selection of unlocked cells only
Sheets("Sheet1").EnableSelection = xlUnlockedCells

End Sub

Don’t allow selection of any cells

Sub NoSelectionAllowed()

'Do not allow selection of any cells
Sheets("Sheet1").EnableSelection = xlNoSelection

End Sub

Allowing VBA code to make changes, even when protected

Even when protected, we still want our macros to make changes to the sheet. The following VBA code changes the setting to allow macros to make changes to a protected sheet.

Sub AllowVBAChangesOnProtectedSheet()

'Enable changes to worksheet by VBA code, even if protected
Sheets("Sheet1").Protect Password:="myPassword", _
    UserInterfaceOnly:=True

End Sub

Unfortunately, this setting is not saved within the workbook. It needs to be run every time the workbook opens. Therefore, calling the code in the Workbook_Open event of the Workbook module is probably the best option.

Allowing the use of the Group and Ungroup feature

To enable users to make use of the Group and Ungroup feature of protected sheets, we need to allow changes to the user interface and enable outlining.

Sub AllowGroupingAndUngroupOnProtectedSheet()

'Allow user to group and ungroup whilst protected
Sheets("Sheet1").Protect Password:="myPassword", _
    UserInterfaceOnly:=True

Sheets("Sheets1").EnableOutlining = True

End Sub

As noted above the UserInterfaceOnly setting is not stored in the workbook; therefore, it needs to be run every time the workbook opens.

Conclusion

Wow! That was a lot of code examples; hopefully, this covers everything you would ever need for using VBA to protect and unprotect sheets.

Related posts:

  • Office Scripts – Workbook & worksheet protection
  • VBA Code to Password Protect an Excel file
  • VBA code to Protect and Unprotect Workbooks

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

Содержание

  1. Метод Workbook.Protect (Excel)
  2. Синтаксис
  3. Параметры
  4. Поддержка и обратная связь
  5. Worksheet.Protect method (Excel)
  6. Syntax
  7. Parameters
  8. Remarks
  9. Support and feedback
  10. VBA Protect Sheet — Как защитить лист в Excel, используя код VBA?
  11. Excel VBA Protect Sheet
  12. Синтаксис VBA Protect Sheet
  13. Как защитить лист в Excel VBA?
  14. VBA Protect Sheet — Пример № 1
  15. VBA Protect Sheet — Пример № 2
  16. То, что нужно запомнить
  17. Рекомендуемые статьи

Метод Workbook.Protect (Excel)

Защищает книгу, чтобы ее нельзя было изменить.

Синтаксис

expression. Защита (пароль, структура, Windows)

Выражение Переменная, представляющая объект Workbook .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Password Необязательный Variant Строка, указывающая пароль для листа или книги с учетом регистра. Если этот аргумент опущен, можно снять защиту листа или книги, не используя пароль. В противном случае необходимо указать пароль для отмены защиты листа или книги. Если вы забыли пароль, вы не сможете снять защиту листа или книги.

Используйте надежные пароли, содержащие строчные и прописные буквы, цифры и знаки. В слабых паролях эти элементы не комбинируются. Надежный пароль: Y6dh!et5. Слабый пароль: House27.

Длина паролей должна быть не меньше 8 символов. В парольной фразе лучше использовать 14 или более символов.

Очень важно запомнить пароль. Если вы его забудете, корпорация Майкрософт не сможет его восстановить. Храните пароли, записанные на бумаге, в безопасном месте вдали от информации, которую они защищают. Структура Необязательный Variant Значение true для защиты структуры книги (относительное положение листов). Значение по умолчанию — False. Windows Необязательный Variant Значение true для защиты окон книги. Если этот аргумент опущен, окна не будут защищены.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Worksheet.Protect method (Excel)

Protects a worksheet so that it cannot be modified.

Syntax

expression.Protect (Password, DrawingObjects, Contents, Scenarios, UserInterfaceOnly, AllowFormattingCells, AllowFormattingColumns, AllowFormattingRows, AllowInsertingColumns, AllowInsertingRows, AllowInsertingHyperlinks, AllowDeletingColumns, AllowDeletingRows, AllowSorting, AllowFiltering, AllowUsingPivotTables)

expression A variable that represents a Worksheet object.

Parameters

Name Required/Optional Data type Description
Password Optional Variant A string that specifies a case-sensitive password for the worksheet or workbook. If this argument is omitted, you can unprotect the worksheet or workbook without using a password. Otherwise, you must specify the password to unprotect the worksheet or workbook. If you forget the password, you cannot unprotect the worksheet or workbook.

Use strong passwords that combine uppercase and lowercase letters, numbers, and symbols. Weak passwords don’t mix these elements. Strong password: Y6dh!et5. Weak password: House27. Passwords should be 8 or more characters in length. A pass phrase that uses 14 or more characters is better.

It’s critical that you remember your password. If you forget your password, Microsoft cannot retrieve it. Store the passwords that you write down in a secure place away from the information that they help protect. DrawingObjects Optional Variant True to protect shapes. The default value is True. Contents Optional Variant True to protect contents. For a chart, this protects the entire chart. For a worksheet, this protects the locked cells. The default value is True. Scenarios Optional Variant True to protect scenarios. This argument is valid only for worksheets. The default value is True. UserInterfaceOnly Optional Variant True to protect the user interface, but not macros. If this argument is omitted, protection applies both to macros and to the user interface. AllowFormattingCells Optional Variant True allows the user to format any cell on a protected worksheet. The default value is False. AllowFormattingColumns Optional Variant True allows the user to format any column on a protected worksheet. The default value is False. AllowFormattingRows Optional Variant True allows the user to format any row on a protected worksheet. The default value is False. AllowInsertingColumns Optional Variant True allows the user to insert columns on the protected worksheet. The default value is False. AllowInsertingRows Optional Variant True allows the user to insert rows on the protected worksheet. The default value is False. AllowInsertingHyperlinks Optional Variant True allows the user to insert hyperlinks on the protected worksheet. The default value is False. AllowDeletingColumns Optional Variant True allows the user to delete columns on the protected worksheet, where every cell in the column to be deleted is unlocked. The default value is False. AllowDeletingRows Optional Variant True allows the user to delete rows on the protected worksheet, where every cell in the row to be deleted is unlocked. The default value is False. AllowSorting Optional Variant True allows the user to sort on the protected worksheet. Every cell in the sort range must be unlocked or unprotected. The default value is False. AllowFiltering Optional Variant True allows the user to set filters on the protected worksheet. Users can change filter criteria but can not enable or disable an auto filter. Users can set filters on an existing auto filter. The default value is False. AllowUsingPivotTables Optional Variant True allows the user to use PivotTable reports on the protected worksheet. The default value is False.

In previous versions, if you apply this method with the UserInterfaceOnly argument set to True and then save the workbook, the entire worksheet (not just the interface) will be fully protected when you reopen the workbook. To re-enable the user interface protection after the workbook is opened, you must again apply this method with UserInterfaceOnly set to True.

If you want to make changes to a protected worksheet, it is possible to use the Protect method on a protected worksheet if the password is supplied. Also, another method would be to unprotect the worksheet, make the necessary changes, and then protect the worksheet again.

Unprotected means that the cell may be locked (Format Cells dialog box) but is included in a range defined in the Allow Users to Edit Ranges dialog box, and the user has unprotected the range with a password or has been validated via NT permissions.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Protect Sheet — Как защитить лист в Excel, используя код VBA?

Excel VBA Protect Sheet

Защита рабочего листа — важная задача для тех, кто очень часто работает в Microsoft Excel. Это задача, которая вам нужна для защиты вашего листа от редактирования другим пользователем. Предположим, вы отправляете отчет руководству, а затем руководство сознательно или по ошибке меняет параметры или значения в отчете. Становится беспокойным, чтобы идентифицировать ошибку, и в то же время переделка — это то, что отнимает у вас время. Чтобы преодолеть эту проблему, всегда рекомендуется защитить лист (ы) для редактирования с помощью пароля. Эта опция помогает вам, не позволяя пользователю вносить какие-либо изменения на листе (ах). Вы также можете поделиться паролем с человеком, который предназначен, а также уполномочен вносить изменения. Несмотря на то, что в приложении Excel имеется опция «Защитить рабочий лист» на вкладке «Просмотр», расположенная на ленте Excel, она становится беспокойной, когда вам нужно защитить более одного листа. Это потратит достаточно времени на защиту каждого листа по одному. Вместо этого рекомендуется писать код VBA, который может защитить один или несколько листов из вашей книги для редактирования.

Синтаксис VBA Protect Sheet

Эта встроенная функция VBA, связанная с Worksheet, позволяет защитить лист с помощью пароля. Синтаксис для функции защиты листа VBA следующий:

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

  • Пароль: указывает пароль для листа. Если не указано иное, лист будет защищен без пароля, и пользователь сможет редактировать его без запроса пароля.
  • DrawingObjects: необязательные аргументы, которые позволяют вам защитить различные формы листа. Принимает логические значения. По умолчанию установлено значение ЛОЖЬ.
  • Содержание: Необязательный аргумент. Защищает все объекты. По умолчанию значения установлены в TRUE.
  • Сценарии: защищает все различные сценарии. По умолчанию установлено значение TRUE.
  • UserInterfaceOnly: защищает пользовательский интерфейс, но не макросы. Значение по умолчанию TRUE, если макрос игнорируется, так как пользовательский интерфейс будет защищен.
  • AllowFormattingCells: значение по умолчанию установлено в FALSE, из-за чего пользователь не может отформатировать ячейки листа. Если установлено значение TRUE, пользователь может форматировать ячейки на листе.
  • AllowInsertingColumns: значение по умолчанию установлено в FALSE. Если установлено значение ИСТИНА, пользователь может вставить столбец в лист.
  • AllowInsertingRows: значением по умолчанию является ЛОЖЬ. Если установлено значение TRUE, пользователь может вставлять строки в лист.
  • AllowInsertingHyperlinks: значение по умолчанию установлено в FALSE. Если установлено значение ИСТИНА, пользователь может вставлять гиперссылки на лист.
  • AllowDeletingColumns: значение по умолчанию установлено в FALSE. Если установлено значение ИСТИНА, пользователь может удалить любой столбец с листа.
  • AllowDeletingRows: значением по умолчанию является ЛОЖЬ. Если установлено значение ИСТИНА, пользователь может удалить любое количество строк с листа.
  • AllowSorting: Значением по умолчанию является ЛОЖЬ. Если установлено значение ИСТИНА, пользователь может сортировать данные, представленные на листе.
  • AllowFiltering: значением по умолчанию является ЛОЖЬ. Если установлено значение ИСТИНА, пользователь может фильтровать данные, представленные на листе.
  • AllowUsingPivotTables: Значением по умолчанию является ЛОЖЬ. Если установлено значение TRUE, пользователь может использовать и изменять сводные таблицы.

Как защитить лист в Excel VBA?

Ниже приведены различные примеры защиты листа в Excel с использованием VBA Protect.

Вы можете скачать этот шаблон Excel для защиты листа VBA здесь — Шаблон Excel для защиты листа VBA

VBA Protect Sheet — Пример № 1

Предположим, у нас есть лист с именем «Пример 1» в книге под названием «VBA Protect Sheet». Мы хотим, чтобы этот лист был защищен паролем. Для этого выполните следующие шаги:

Шаг 1. Вставьте новый модуль в редактор Visual Basic (VBE). Нажмите на Вставить > выбрать модуль .

Шаг 2: Определите новую подпроцедуру в модуле.

Код:

Шаг 3: Теперь мы должны использовать функцию Protect, которую можно применить к объекту с именем Worksheet. Запустите код с объектом Worksheets и введите имя листа в скобках, которое вы хотите защитить.

Код:

Шаг 4: Теперь поставьте точку после закрывающих скобок и используйте ключевое слово Protect, которое инициирует процесс защиты листа с именем « Пример 1 ».

Код:

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

Шаг 5: Введите ключевое слово Password и используйте надежный пароль для защиты этого листа.

Код:

Мы будем использовать только первый аргумент функции, которая называется паролем, а для остальных всех аргументов мы будем использовать значения по умолчанию.

Шаг 6: Вот и все, вы можете запустить этот код, нажав F5 или кнопку Run, и увидите, что файл теперь защищен и попросит пользователя ввести пароль, как только он попытается отредактировать любую из ячеек.

Вот как мы защищаем лист, используя функцию защиты VBA.

VBA Protect Sheet — Пример № 2

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

Шаг 1: Определите подпроцедуру в модуле.

Код:

Шаг 2: Определите новую переменную как рабочий лист, используя Dim.

Код:

Шаг 3: Запустите цикл For. Этот цикл должен выполняться до последнего рабочего листа активной рабочей книги.

Код:

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

Шаг 4: Теперь используйте функцию Protect для защиты листов, хранящихся в переменной wrk_sht для каждой итерации цикла For.

Код:

Шаг 5: Используйте оператор Next, он позволяет циклу работать, пока каждый лист не будет защищен.

Код:

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

То, что нужно запомнить

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

Рекомендуемые статьи

Это руководство по VBA Protect Sheet. Здесь мы обсудим, как защитить или заблокировать листы с помощью функции VBA Protect в Excel, а также на практических примерах и загружаемом шаблоне Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Как переименовать лист в Excel VBA?
  2. Шаги, чтобы снять защиту листа в Excel
  3. Лист активации VBA (Примеры с шаблоном Excel)
  4. Как скопировать лист Excel?

Источник

Home / VBA / How to PROTECT and UNPROTECT a Sheet using VBA in Excel

In VBA, there’s the PROTECT method that you can use with a sheet. In this method, you have the option to protect a sheet, with or without a password. And you can also protect an object from the sheet. We will see all these in detail in this tutorial.

In the tutorial, we will look at how to protect and unprotect a single sheet or multiple sheets using a VBA code.

Write a VBA Code to Protect a Sheet

To protect a sheet, you need to specify the sheet first and then use the protect method. Here are the steps.

  1. Use the sheets object to specify the sheet.
  2. Enter the name of the sheet that you want to protect.
  3. Type a dot to get the list of the methods and properties.
  4. Select the project method or type it.
Sheets("Sheet1").Protect

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Write a VBA Code to Unprotect a Sheet

To protect a sheet, you need to specify the sheet first and then use the unprotect method. Here are the steps.

  1. Specify the sheet using the sheet object.
  2. And then, enter the name of the sheet that you want to protect.
  3. Enter a dot to get the list of the methods and properties.
  4. Select the “Unprotect” method or type it.
Sheets("Sheet1").Unprotect

Protect a Sheet with Password

If you want to set a password while protecting a sheet, in that case, you need to use the password argument to specify a password. Let’s say if you want to set a password “test123” to the sheet for protecting it, the code would be like the below.

Sheets("Sheet1").Protect Password:="test123"

Unprotect a Sheet with Password

In the same way, if you want to unprotect a sheet, you need to mention the password in the password argument. Let’s say the password that you have used to protect the sheet is “ADSBP” so the code to unprotect it would be like below.

Sheets("Sheet1").Unprotect Password:="ADSBP"

There’s one thing that you need to take care, take care of capital letter as VBA differentiate between capital and small letters.

Other Things to Know

As I said, we are using VBA’s “Protect” method, and there are arguments other than “Password” with this method that you can use.

expression.Protect (Password, DrawingObjects, Contents, Scenarios, UserInterfaceOnly, AllowFormattingCells, AllowFormattingColumns, AllowFormattingRows, AllowInsertingColumns, AllowInsertingRows, AllowInsertingHyperlinks, AllowDeletingColumns, AllowDeletingRows, AllowSorting, AllowFiltering, AllowUsingPivotTables)
  1. DrawingObjects: To protect and unprotect shapes.
  2. Contents: TO protect cells that are locked and the entire chart.
  3. Scenarios: To protect scenarios in the worksheet.
  4. UserInterfaceOnly: To only protect the user interface not macros.
  5. AllowFormattingCells: To allow the user to apply formatting to cells.
  6. AllowFormattingColumns: To allow the user to apply formatting to columns.
  7. AllowFormattingRows: To allow the user to apply formatting to rows.
  8. AllowInsertingColumns: To allow the user to insert new columns.
  9. AllowInsertingRows: To allow the user to insert new rows.
  10. AllowInsertingHyperlinks: To allow the user to create hyperlinks.
  11. AllowDeletingColumns: To allow the user to delete columns.
  12. AllowDeletingRows: To allow the user to delete rows.
  13. Allow Sorting: To allow the user to sort rows, columns, and tables.
  14. AllowFiltering: To allow filtering columns.
  15. AllowUsingPivotTables: To let the user use a pivot table.

Notes

  • Make sure to use strong passwords that combine uppercase and lowercase letters, numbers, and symbols.
  • If you forget your password, Microsoft cannot retrieve it. So, make sure to write down your password somewhere in a safe place.
  • If a sheet protected without a password, and now you want to protect it with a password, you need to unprotect it first. And then reprotect it with a password using the code you have seen above.

More Tutorials on VBA Worksheets

  • Back to VBA Worksheet / VBA Tutorial

Понравилась статья? Поделить с друзьями:
  • Защитить лист от вставки строк excel
  • Защитить лист excel что это
  • Защитить лист excel от редактирования кроме нескольких ячеек
  • Защитить лист excel от редактирования vba
  • Защитить лист excel не активен