Vba excel защита ячейки

 

Marshal

Пользователь

Сообщений: 83
Регистрация: 27.12.2012

#1

18.10.2016 02:18:33

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

Но данная защита снимается нажатием правой кнопкой на листе «Снять защиту листа».
Что можно сделать дабы исключить такую возможность вообще или снятие через пароль, но на VBA.

Всем спасибо

Код
Private Sub Workbook_Open()
   Cells.Locked = False '
    Range("F5:AH5").Locked = True
    ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
End Sub

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#2

18.10.2016 02:22:31

Код
Protect("abracadabra")
Unprotect("abracadabra")
 

Marshal

Пользователь

Сообщений: 83
Регистрация: 27.12.2012

Спасибо за ответ. с этим я и воююю
Не могу прикрутить

 

k61

Пользователь

Сообщений: 2441
Регистрация: 21.12.2012

#4

18.10.2016 02:51:08

Прикрутка:

Код
....
ActiveSheet.Protect Password:="abracadabra", DrawingObjects:.......
....
 

Marshal

Пользователь

Сообщений: 83
Регистрация: 27.12.2012

#5

18.10.2016 04:25:06

Спасибо большое, прикрутил.
Не знаю на сколько правильно. Все ячейки кроме указанных не заблокированы.

Код
Private Sub Workbook_Open()
 Sheets("Лист1").Select
ActiveSheet.Unprotect Password:="321"
    Range("B8:AH8").Locked = True
    ActiveSheet.Protect Password:="321"
End Sub

I want to stop others from editing the cell contents in my excel sheet using VBA. Is it possible to do this?

armstrhb's user avatar

armstrhb

4,0243 gold badges20 silver badges28 bronze badges

asked Jun 14, 2010 at 13:05

raam's user avatar

1

You can first choose which cells you don’t want to be protected (to be user-editable) by setting the Locked status of them to False:

Worksheets("Sheet1").Range("B2:C3").Locked = False

Then, you can protect the sheet, and all the other cells will be protected.
The code to do this, and still allow your VBA code to modify the cells is:

Worksheets("Sheet1").Protect UserInterfaceOnly:=True

or

Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)

answered Jun 14, 2010 at 17:31

Lance Roberts's user avatar

Lance RobertsLance Roberts

22.2k32 gold badges112 silver badges129 bronze badges

5

Try using the Worksheet.Protect method, like so:

Sub ProtectActiveSheet()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    ws.Protect DrawingObjects:=True, Contents:=True, _
        Scenarios:=True, Password="SamplePassword"
End Sub

You should, however, be concerned about including the password in your VBA code. You don’t necessarily need a password if you’re only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.

Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That’s a good way to get started in VBA.

answered Jun 14, 2010 at 13:54

Ben McCormack's user avatar

Ben McCormackBen McCormack

31.8k46 gold badges145 silver badges221 bronze badges

Let’s say for example in one case, if you want to locked cells from range A1 to I50 then below is the code:

Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"

In another case if you already have a protected sheet then follow below code:

ActiveSheet.Unprotect Password:="Enter your Password"
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"

answered Sep 18, 2013 at 9:40

Milan Sheth's user avatar

Milan ShethMilan Sheth

84412 silver badges10 bronze badges

You can also do it on the worksheet level captured in the worksheet’s change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect…

Private Sub Worksheet_Change(ByVal Target As Range)

    'set your criteria here
    If Target.Column = 1 Then

        'must disable events if you change the sheet as it will
        'continually trigger the change event
        Application.EnableEvents = False
        Application.Undo
        Application.EnableEvents = True

        MsgBox "You cannot do that!"
    End If
End Sub

answered Jun 15, 2010 at 15:28

Fink's user avatar

FinkFink

3,31619 silver badges26 bronze badges

Sub LockCells()

Range("A1:A1").Select

Selection.Locked = True

Selection.FormulaHidden = False

ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= False, AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True

End Sub

answered Jun 14, 2010 at 21:41

krusaint's user avatar

I want to stop others from editing the cell contents in my excel sheet using VBA. Is it possible to do this?

armstrhb's user avatar

armstrhb

4,0243 gold badges20 silver badges28 bronze badges

asked Jun 14, 2010 at 13:05

raam's user avatar

1

You can first choose which cells you don’t want to be protected (to be user-editable) by setting the Locked status of them to False:

Worksheets("Sheet1").Range("B2:C3").Locked = False

Then, you can protect the sheet, and all the other cells will be protected.
The code to do this, and still allow your VBA code to modify the cells is:

Worksheets("Sheet1").Protect UserInterfaceOnly:=True

or

Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)

answered Jun 14, 2010 at 17:31

Lance Roberts's user avatar

Lance RobertsLance Roberts

22.2k32 gold badges112 silver badges129 bronze badges

5

Try using the Worksheet.Protect method, like so:

Sub ProtectActiveSheet()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    ws.Protect DrawingObjects:=True, Contents:=True, _
        Scenarios:=True, Password="SamplePassword"
End Sub

You should, however, be concerned about including the password in your VBA code. You don’t necessarily need a password if you’re only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.

Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That’s a good way to get started in VBA.

answered Jun 14, 2010 at 13:54

Ben McCormack's user avatar

Ben McCormackBen McCormack

31.8k46 gold badges145 silver badges221 bronze badges

Let’s say for example in one case, if you want to locked cells from range A1 to I50 then below is the code:

Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"

In another case if you already have a protected sheet then follow below code:

ActiveSheet.Unprotect Password:="Enter your Password"
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"

answered Sep 18, 2013 at 9:40

Milan Sheth's user avatar

Milan ShethMilan Sheth

84412 silver badges10 bronze badges

You can also do it on the worksheet level captured in the worksheet’s change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect…

Private Sub Worksheet_Change(ByVal Target As Range)

    'set your criteria here
    If Target.Column = 1 Then

        'must disable events if you change the sheet as it will
        'continually trigger the change event
        Application.EnableEvents = False
        Application.Undo
        Application.EnableEvents = True

        MsgBox "You cannot do that!"
    End If
End Sub

answered Jun 15, 2010 at 15:28

Fink's user avatar

FinkFink

3,31619 silver badges26 bronze badges

Sub LockCells()

Range("A1:A1").Select

Selection.Locked = True

Selection.FormulaHidden = False

ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= False, AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True

End Sub

answered Jun 14, 2010 at 21:41

krusaint's user avatar

Users entering data into the wrong cells or changing existing formulas can make data collection a tedious process. However, you can prevent users from going outside the intended boundaries by disabling certain sections of your workbook. In this article, we’re going to show you how to lock a cell in Excel formula using VBA.

Protection

Worksheets are objects in a workbook’s worksheet collection and they have Protect and Unprotect methods. These methods determine the protected status of a worksheet as the name suggests. Both methods can get accept other optional arguments. The first is the password argument. By setting a string for the parameter argument, you can lock your worksheets with a password. Below is a breakdown.

Code sample

Lock Cells

Important note: Protecting a sheet does not lock individual cells! The cells you want to lock should be marked as Locked too. A cell can be marked as Locked, and/or Hidden, in two ways:

  • Via user interface
  • Via VBA

The User Interface method requires using the Format Cells dialog. Select a cell or a range of cells, and press Ctrl + 1 to open this menu and go to the Protection tab. Use the corresponding checkboxes to activate properties.

Format Cells Protection

The second method is doing this via VBA code. Every cell and range can be made Locked and FormulaHidden properties. Set these two as True or False to change their status.

Activecell.Locked = True

Activecell.FormulaHidden = True

You can use the Hidden status to hide your formulas as well.

Detect Cells with Formulas

If you just need to lock only cells with formulas, you need to first identify cells that have formulas. The cells and ranges have a HasFormula property, which makes them read only. It returns a Boolean value based on whether the cell or range has a formula. A simple loop can be used to detect cells in a given range that contain formula.

    For Each rng In ActiveSheet.Range("B4:C9")

        If rng.HasFormula Then

            rng.Locked = True

        Else

            rng.Locked = False

        End If

    Next rng

To run this code, you need to add a module into the workbook or the add-in file. Copy and paste the code into the module to run it. The main advantage of the module method is that it allows saving the code in the file, so that it can be used again later. Furthermore, the subroutines in modules can be used by icons in the menu ribbons or keyboard shortcuts. Remember to save your file in either XLSM or XLAM format to save your VBA code.

Lock cells and protect a worksheet

The code example below checks every cell in the range «B4:C9» from the active worksheet. If a cell has a formula, it locks the cell. Otherwise, the cell becomes or remains unlocked.

Sub ProtectCellsWithFormulas()

      For Each rng In ActiveSheet.Range("B4:C9")

          If rng.HasFormula Then

              rng.Locked = True

          Else

              rng.Locked = False

          End If

      Next rng

ActiveSheet.Protect "pass"

End Sub

Содержание

  1. Worksheet.Protect method (Excel)
  2. Syntax
  3. Parameters
  4. Remarks
  5. Support and feedback
  6. Метод Worksheet.Protect (Excel)
  7. Синтаксис
  8. Параметры
  9. Замечания
  10. Поддержка и обратная связь

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.

Источник

Метод Worksheet.Protect (Excel)

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

Синтаксис

expression. Защита (Password, DrawingObjects, Contents, Scenarios, UserInterfaceOnly, AllowFormattingCells, AllowFormattingColumns, AllowFormattingRows, AllowInsertingColumns, AllowInsertingRows, AllowInsertingHyperlinks, AllowDeletingColumns, AllowDeletingRows, AllowSorting, AllowFiltering, AllowUsingPivotTables )

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

Параметры

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

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

Очень важно запомнить пароль. Если вы его забудете, корпорация Майкрософт не сможет его восстановить. Храните пароли, записанные на бумаге, в безопасном месте вдали от информации, которую они защищают. DrawingObjects Необязательный Variant Значение true для защиты фигур. Значение по умолчанию — True. Contents Необязательный Variant Значение true для защиты содержимого. Для диаграммы это защищает всю диаграмму. Для листа это защищает заблокированные ячейки. Значение по умолчанию — True. Scenarios Необязательный Variant Значение true для защиты сценариев. Этот аргумент действителен только для листов. Значение по умолчанию — True. UserInterfaceOnly Необязательный Variant Значение true для защиты пользовательского интерфейса, но не макросов. Если этот аргумент опущен, защита применяется как к макросам, так и к пользовательскому интерфейсу. AllowFormattingCells Необязательный Variant Значение True позволяет пользователю форматировать любую ячейку на защищенном листе. Значение по умолчанию — False. AllowFormattingColumns Необязательный Variant Значение True позволяет пользователю форматировать любой столбец на защищенном листе. Значение по умолчанию — False. AllowFormattingRows Необязательный Variant Значение True позволяет пользователю форматировать любую строку на защищенном листе. Значение по умолчанию — False. AllowInsertingColumns Необязательный Variant Значение True позволяет пользователю вставлять столбцы на защищенный лист. Значение по умолчанию — False. AllowInsertingRows Необязательный Variant Значение True позволяет пользователю вставлять строки на защищенный лист. Значение по умолчанию — False. AllowInsertingHyperlinks Необязательный Variant Значение True позволяет пользователю вставлять гиперссылки на защищенный лист. Значение по умолчанию — False. AllowDeletingColumns Необязательный Variant Значение True позволяет пользователю удалять столбцы на защищенном листе, где каждая ячейка удаляемого столбца разблокирована. Значение по умолчанию — False. AllowDeletingRows Необязательный Variant Значение True позволяет пользователю удалять строки на защищенном листе, где каждая ячейка в удаляемой строке разблокирована. Значение по умолчанию — False. AllowSorting Необязательный Variant Значение True позволяет пользователю выполнять сортировку на защищенном листе. Каждая ячейка в диапазоне сортировки должна быть разблокирована или не защищена. Значение по умолчанию — False. AllowFiltering Необязательный Variant Значение True позволяет пользователю задавать фильтры на защищенном листе. Пользователи могут изменять условия фильтра, но не могут включать или отключать автоматический фильтр. Пользователи могут задавать фильтры для существующего автофильтра. Значение по умолчанию — False. AllowUsingPivotTables Необязательный Variant Значение True позволяет пользователю использовать отчеты сводной таблицы на защищенном листе. Значение по умолчанию — False.

Замечания

В предыдущих версиях, если применить этот метод с аргументом UserInterfaceOnly , равным True , а затем сохранить книгу, при повторном открытии книги будет полностью защищен весь лист (а не только интерфейс). Чтобы повторно включить защиту пользовательского интерфейса после открытия книги, необходимо снова применить этот метод, если параметр UserInterfaceOnly имеет значение True.

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

Незащищено означает, что ячейка может быть заблокирована (диалоговое окно Форматирование ячеек ), но включена в диапазон, определенный в диалоговом окне Разрешить пользователям изменять диапазоны , и пользователь отключил защиту диапазона паролем или был проверен с помощью разрешений NT.

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

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

Источник

Понравилась статья? Поделить с друзьями:
  • Vba excel имена открытых книг
  • Vba excel изменить размер шрифта
  • Vba excel защита ячеек от редактирования
  • Vba excel имена всех файлов в папке
  • Vba excel изменить размер массива