Excel VBA Project Password
Excel VBA Project Password is a kind of tool in VBA which is used to protect the project code using the password. By this, we can protect the worksheet and the projects as well. If we protect the project, in another way we are also protecting the Excel workbook as well. We can either protect or preserve one project in VBA or multiple projects. And this is can be using the same procedure for both categories.
Usually, most of the code written in VBA has or requires only a project in which all the worksheets, modules, user forms can be seen.
How to Use VBA Project Password in VBA?
To protect the VBA Project using Password or to enable the password set in a VBA Project, we will be using the VBA Project properties option which is available in the Tools menu bar in VBA as shown in the below steps. Then we will be getting the VBA Project properties window where we can set the password whichever we want, to protect the currently available projects in VBA.
You can download this VBA Project Password Excel Template here – VBA Project Password Excel Template
Example #1
To apply a password in the VBA Project, first, we need to have a code in a module. This could be any simple code as per our choice or requirement. For this, follow the below steps:
Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.
Step 2: Now write the subprocedure for the VBA Project password.
Code:
Sub VBA_ProjectPW() End Sub
Step 3: Use DIM to define a variable as an Integer.
Code:
Sub VBA_ProjectPW() Dim A As Integer End Sub
Step 4: And last to close the code, use Debug print to print the value whichever could be stored in variable A. This is the simplest code that we protect using the VBA Project password.
Code:
Sub VBA_ProjectPW() Dim A As Integer Debug.Print A End Sub
Step 5: To test this, we would run this code by pressing F5 or Play Button is mentioned below the menu bar.
We would notice that the code has run without any error. Now to protect the VBA Project with a password, go to Tools menu option and select VBA Project properties as shown below.
Step 6: We will then get the Project Properties as shown below. And in that go to the Protection tab.
Step 7: Now in the Protection tab’s Password and Confirm password section write the password which you want. Preferably the password should be strong enough not be cracked easily by anyone.
Step 8: We have chosen the password as “Pa$$w0rd123” in the combination of Upper case, lower case, special character, and numbers. The password should be the same in Password and Confirm Password section as shown below. It is better to copy and paste the password to match and then Click on OK to exit.
Step 9: Now save the code and then close the VBA and Excel files. To check this, reopen the file. In the VBA window, we will see all the options like Modules in the VBA Project is hidden. To test, click on the plus sign of the VBA Project.
Step 10: We will get the password window there. To enter the password which we had chosen. And then click on Ok.
Step 11: This would enable the VBA Project with all the options and we will be able to see the code written in the module.
Step 12: And if we enter the incorrect password we would then get an incorrect message alert.
Example #2
There is another way to protect the VBA Project using passwords with the help of code. For this, follow the below steps:
Step 1: In the same module and write the subprocedure.
Code:
Sub VBA_ProjectPW2() End Sub
Step 2: Now write define a variable using DIM as a Variant.
Code:
Sub VBA_ProjectPW2() Dim PW As Variant End Sub
Step 3: In the defined variable PW we will use the Input Box application and choose the title and message which we would like to see.
Code:
Sub VBA_ProjectPW2() Dim PW As Variant PW = Application.InputBox("Enter Password", "Password Protected") End Sub
Step 4: Open the Select Case-Else loop and there write the condition where if the entered password is “Pa$$w0rd123” then we would get the message as secured workbook in select range cell.
Code:
Sub VBA_ProjectPW2() Dim PW As Variant PW = Application.InputBox("Enter Password", "Password Protected") Select Case PW Case Is = False Case Is = "Pa$$w0rd123" Range("A1").Value = "Workbook is secured." Case Else End Sub
Step 5: And to see if the entered password is incorrect then we would get a message as Incorrect Password.
Code:
Sub VBA_ProjectPW2() Dim PW As Variant PW = Application.InputBox("Enter Password", "Password Protected") Select Case PW Case Is = False Case Is = "Pa$$w0rd123" Range("A1").Value = "Workbook is secured." Case Else MsgBox "Incorrect Password" End Select End Sub
Step 6: Now if we run the code by pressing F5 or the Play Button is mentioned below the menu bar, we would get the Password Protected window where we would enter the password. If the password entered is correct then this window will be closed.
Step 7: Once entered, click on Ok.
Step 8: We would see the code has run successfully. And the cell A1 would have the message which chose in VBA Code as “Workbook is secured.”
Pros of VBA Project Password
- This is helpful is securing the very confidential code which we probably do not want to show to anyone.
- VBA Project protected using the methods which we have seen in the above examples is best to secure the code.
Things to Remember
- Password entered using VBA Project Password can be cracked using the alternate add-ins available and can be downloaded from the internet or Microsoft website.
- Make sure the password entered is easy to enter, easy to remember. Or else keep the note so that it is not lost. If by any chance the entered password is incorrect then it is hard to recover it.
- If the excel is not saved in the format of Macro Enable format then the written code will be lost.
- VBA Project Password is different from the method of protecting the Excel file using Protect Sheet, Protect Workbook available in Review menu bar.
Recommended Articles
This is a guide to the VBA Project Password. Here we discuss how to protect the project code using the password in excel VBA along with practical examples and a downloadable excel template. You can also go through our other suggested articles –
- How to Use VBA Login?
- VBA Month | Examples With Excel Template
- How to Use Create Object Function in VBA Excel?
- How to Use VBA IsError Function?
Is it possible to break into my Excel VBA project if the code is protected with a lost or forgotten password? And if so, how can this be done? The answer is yes. Cracking an Excel VBA password is not a difficult task if you have the right tools. In fact, once you have the right tool and methodology in place, it can be quite easy to crack even complicated passwords.
In this article, we will show you how to hack VBA passwords by using a few simple methods. But first let’s take a look at what VBA password is in Excel.
VBA Password—How Does It Work?
VBA (Visual Basic for Applications) is a programming language used to make Microsoft Office applications such as Excel and Access more powerful and easier to use. VBA is also used to create custom applications.
A VBA project can be protected with a password to prevent unauthorized access. When you open a VBA project in Excel spreadsheet, you may be prompted to enter the password (as the image shown below). If you do not enter the correct password, you will not be able to view or edit the VBA code.
How to Crack an Excel VBA Password
There are a few different methods that can be used to crack an Excel VBA password. We will look at each of these methods in detail below.
Method 1: Using VBA Password Reset a
“VBA Password Reset a” is a powerful Excel password recovery plugin that can quickly reset the password to “a” from most VBA projects. This tool is compatible with Excel 2007 and above on a Windows computer, as well as Excel 2016 and higher on a Mac.
The Excel VBA Password Reset a add-in, once installed and enabled, will be accessible from the Excel ribbon. It takes only two actions to remove a macro password in Excel.
Step 1. Open workbook file with password prompt—click on “Reset VBA password – a”.
Step 2. Select an option to reset the password—here we may select “Unprotect all sheets in active workbook” from the menu.
You will be given a copy of your Excel file at the same location as where it was originally created and with an “a” VBA password.
Method 2: Using SysTools VBA Password Remover
SysTools introduced a Windows application called “SysTools VBA Password Remover” for Excel 97 and later versions. This program will crack VBA passwords in Excel workbooks easily without any technical knowledge required.
Step 1. Click the button below and download this program.
Free Download
Step 2. After you’ve launched the program, you’ll see a page with the heading “Check for Prerequisites”, where we need to click “OK” in order continue.
Step 3. Select the Excel workbook with encrypted content using the “Add File(s)” button. Then click “Reset” in order to unlock all its VBA codes.
Step 4. Now you can see that a new password has been set for this file and the status says “Pass”, which means this will be the password for accessing your VBA project.
Method 3: Change Extension + Hex Editor
In order to reset or remove a password from an Excel workbook using Hex Editor, we first need to back up the file that has been protected by VBA password. After you have backed up the file, follow these steps:
Step 1. Change the Excel file extension from “xlsm” to “zip”. This will make the file appear to be a ZIP archive.
For many people, the “Hide extensions for known file types” box in Folder Options is checked by default. Unchecking this box will make extensions visible in File Explorer.
Step 2. Extract the ZIP file with a tool like WinZip or 7-Zip.
Step 3. Open up the unzipped folder. Inside of this one there is an “xl” subfolder where you can find the “vbaProject.bin” file.
Step 4. Open the “vbaProject.bin” file with a hex editor such as HxD.
Step 5. Look for “DPB” within the file.
Step 6. Now change “DPB” to “DPx”. Save the changes and exit.
Only “B” should be changed to “x”, and don’t eliminate the equal sign by mistake.
Step 7. Compress all the folders and files to a ZIP.
Step 8. Change the extension from “zip” to “xlsm”, and then opening it.
Step 9. Okay, so you’re in the xlsm file. The first thing that may happen is a lot of errors popping up but don’t worry: just press “Yes” to dismiss them.
Open the VB editor by clicking “Developer” then “Visual Basic”. Then, under “Tools” > “VBAProject Properties”, remove the check for “Lock project for viewing”.
Step 10. Close the editor and save the Excel file. It’s possible that it’ll notify you to save in a different location as a new file.
Step 11. Open the new file. Your VBA code will now be visible without the need to enter a password!
*We have tested this method on an Excel 2007 file.
Conclusion
VBA Password has been used by many developers in order to protect their code from being seen or edited by other people who will misuse it. This is a good technique in most cases, but when you forget your Excel VBA password and need to see your project code, the above methods will help you.
In this article we’ve covered three ways you can gain access to your VBA project without the need of a password. Whether you want to use an add-in tool or download a password remover program from SysTools, it doesn’t take long before your file is open and available for editing again.
Susanna is the content manager and writer of Filelem. She has been an experienced editor and book layout designer for many years, and interested in trying and testing various productivity software. She is also a huge fan of Kindle, who has been using Kindle Touch for nearly 7 years and carrying Kindle almost wherever she goes. Not long ago the device was at the end of its life so Susanna happily bought a Kindle Oasis.
Время на прочтение
5 мин
Количество просмотров 25K
Всем привет! Я обычный пользователь MS Excel. Не являющийся профессиональным программистом, но накопивший достаточно опыта, для установки и обхода защиты проектов VBA.
Дисклеймер:
В данной статье рассмотрены виды защиты проектов VBA, от несанкционированного доступа. Их сильные и слабые стороны – ранжирование.
Цель статьи показать слабые и сильные стороны каждого вида защиты проекта VBA в MS Office.
Демонстрация разработанных инструментов, в надстройке Macro Tools VBA, для снятия и установки той или иной защиты.
Все инструменты реализованы стандартными средствами VBA, без использования дополнительных библиотек.
Главная панель Надстройки Macro Tools VBA
Первый вид защиты — Обычный пароль
Время на снятие: мгновенно
Недостаток: быстрый доступ к запароленному модулю VBA
Стандартный инструмент (В среде VBE: панель Tools -> VBAProject Properties -> Protection).
Самая легко снимающаяся защита. В интернете легко находится код, для снятия данной защиты.
Данную защиту можно снять следующим инструментом:
Второй вид защиты — Project is Unviewable
Время на снятие: от 10 до 15 мин (в ручную)
Недостаток: доступ к исходному коду модуля VBA
Один из самых распространённых видов защит. Встречается в 95% файлах с защитой модуля VBA. При попытке открыть проект, открывается диалоговое окно, с сообщением: Project is Unviewable.
Большинство пользователей Excel, не могут снять данную защиту, так как она имеет множество вариации и нюансов, для ее снятие нужно иметь представление о внутренней структуре файла Excel.
Основан, данный вид защиты, на изменение ключей:
CMG=«4A488FCC54D054D054D054D0»
DPB=«0B09CE0F8E108E108E»
GC=«CCCE09520B120C120CED»
в файле vbaProject.bin
.
Кратко, как создается данная защита
Для создания данной защиты нужно, разархивировать файл Excel. Перейти в архиве в папку xl, открыть файл vbaProject.bin, в конце файла находятся наши ключи, редактируем значения ключей на пусто, сохраняем файл. Переводим наш архив, обратно в файл Excel. Готово!
Это самый простой вариант данной защиты, но существует множество модификаций.
Алгоритм снятия защиты Project is Unviewable.
1) Разархивируем подопытный файл, переходим в файл …xl_relsworkbook.xml.rels
2) В файле workbook.xml.rels ищем строку, содержащую слово vbaProject, обычно имеет следующий вид: />. В этой строке нас интересует ключ Target,иего значение. Значение является название файла, в котором находится проект VBA. Иногда, защищающий меняет значения ключа на printerSettings.bin.Получается маскировка файла с проектом VBA под другой файл.
3) Открываем на редактирование файл, указанный в ключе Target, ищем в файле ключи CMG, DPB, GC. И меняем в их названиях любую букву на любую другую, например: CMC, DPC, CC. При поиске нужно быть аккуратным, так как защищающий может поместить в проект форму, подписью повторяющую один из ключей, например такую: DPB=«0B09CE0F8E108E108E». При ее изменении проект VBA, будет удален из книги Excel. Сохраняем и закрываем файл.
4) Переводим архив обратно в файл Excel.
5) Запускаем приложение Excel, выполняем следующее: в Центре управления безопасностью -> Параметры макросов -> Отключить все макросы без уведомления. Перезапускаем Excel. Данная операция нужна, для блокировки защиты, которую иногда ставят авторы макросов. Данная защита реализована следующим образом. В модуле VBA «ЭтаКнига», создается процедуры, реагирующие на события открытия книги или закрытия книги. Эти события обычно проверяют, наличие пароля на проект VBA, запрет сохранения и прочее.
6) Открываем файл. Если все правильно сделано то, Excel, будет ругаться на не правильные ключи, которые мы отредактировали, в пункте 3. Жмем, да, пока данные сообщения не закончатся и диалоговое окно закроется.
Если данное сообщение не появляется то, вы отредактировали не файл который содержит проект VBA.
7) Открываем проект VBA. После всего, проект VBA должен быть доступен.
Но иногда защита не снимается, тогда нужно сохранить файл, проверить, что он действительно сохранился! И проделать повторно операции с 1 по 7. Обычно так происходит когда в файле workbook.xml.rels в ключе Target установлено printerSettings.bin.При сохранение, Excel исправляет это на значение на vbaProject.bin
Данную защиту можно установить и снять следующим инструментом:
Третий вид защиты — Hidden Module, скрытые модули VBA
Время на снятие: от 15 до 20 мин (нужен редактор OLE — объектов, Structured Storage Viewer, например.
Недостаток: доступ к коду модуля VBA
Менее распространенный вид защиты обычно встречается в комбинации с защитой Project is Unviewable. При установке данной защиты модуль VBA не отображается в проекте книги Excel. О его существовании можно узнать, проанализировав код VBA (что требует время!) или открыть файл Excel в программе OpenOffice или LibreOffice (так же можно смотреть код при защите Project is Unviewable, но данный способ не дает возможность получить рабочий файл, без пароля).
Просмотр кода VBA в LibreOffice
Кратко, как создается данная защита
Для создания данной защиты нужно отредактировать файл с проектом VBA — vbaProject.bin или printerSettings.bin,в зависимости от настроек в файле …xl_relsworkbook.xml.rels. В конце файла удаляются строки вида: Module1=32, 32, 635, 330, Z. С нужными названиями модулей.
Для снятия данной защиты нужно в файле vbaProject.bin — восстановить удаленные записи модулей.
Данную защиту можно установить следующим инструментом.
Четвертый вид защиты — Обфускация кода
Время на снятие: неизвестно, зависит от объема кода и пере использования частей кода
Обфусцированный код VBA
Недостаток: необходимость тестирование файла после обфускации, на работоспособность
Крайне редкий вид защиты, основанный на изменении исходного кода VBA, в не удобочитаемый вид для человека. Удаляются все комментарии, форматирование кода, переименовываются названия всех переменных, процедур, функций, модулей и прочего. Злоумышленнику никогда не удастся восстановить первоначальный вид кода, и потребует достаточно много времени для, его восстановления в удобно читаемый вид для человека.
Для де-обфускации кода нужно иметь время, специализированное ПО.
Данную защиту можно установить следующим инструментом.
Пятый вид защиты — Перенос кода в dll
Время на снятие: неизвестно, зависит от языка программирования и квалификации
Недостаток: необходимости в дополнительном файле dll
Один из самых редких видов защиты. Основная идея перенос основного кода в отдельную библиотеку dll, написанную на любом другом языке программирования. Не распространённость данный вид защиты получил по следующей причине, необходимости за файлом Excel, «таскать» дополнительный файл, dll.
Для получения доступа к коду dll, нужно обладать специальными знаниями.
Заключение
В заключении хочу выделить бесполезность защит: Project is Unviewable и Hidden Module которые, по существу ни отчего не защищают. Позволяют просматривать код VBA, без изменения исходного файла, в таких программах как OpenOffice или LibreOffice. Так и снимаются без особых проблем.
Return to VBA Code Examples
This article will explain how to password protect your VBA projects.
When you create a custom VBA add-in or series of macros for a user, you might like to protect your intellectual copyright, or that of our company’s, by password protecting your code so that it is not easy to copy.
Note: VBA Protection is very easy to get around. You should not rely on this security.
Amending VBA Project Properties
To password protect a VBA Project, we need to amend the VBA Project Properties.
In the VBE Editor, right-click on your VBA Project in the Project Explorer, and then click VBA Project Properties.
First, (1) click on the Protection tab and then, 2) make sure that “Lock project for viewing” is checked. Next (3) in the “Password to view project properties“, type in the password and then confirm the password. Finally (4), click OK.
Note: when creating a password, the more complicated the password, the harder it will be to crack!
Save and Close your file, and then re-open the file and press ALT+F11 to open the VBE Window once again.
Double-click on your VBA Project in order to view the modules and/or forms contained in the Project.
You will be required to enter a password before you can see any of the modules or forms contained in the project.
In this Excel VBA Protect Sheet with Password Tutorial, you learn how to protect a sheet with password using Excel macros.
This Excel VBA Protect Sheet with Password Tutorial is accompanied by an Excel workbook with the data and VBA code I use when describing the step-by-step process below. Get this example workbook (for free) by clicking the button below.
The VBA code in the Excel workbook that accompanies this Excel VBA Protect Sheet with Password Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section below.
The following Excel Macro and VBA Tutorials may help you better understand and implement the contents below.
- Tutorials about general macro and VBA constructs and structures:
- Tutorials for Beginners:
- Excel Macros: Click here to open.
- Excel VBA: Click here to open.
- Enable macros in Excel: Click here to open.
- Work with the Visual Basic Editor (VBE): Click here to open.
- Create Sub procedures: Click here to open.
- Refer to objects (click here to open), including sheets (click here to open).
- Work with:
- Methods: Click here to open.
- Data types: Click here to open.
- Loops: Click here to open.
- Tutorials for Beginners:
- Tutorials with practical VBA applications and macro examples:
- Activate workbook: Click here to open.
- Create new workbook: Click here to open.
- Open workbook: Click here to open.
- Delete sheet: Click here to open.
This Excel VBA Protect Sheet with Password Tutorial is part of a more comprehensive series of Excel VBA Protect or Unprotect Sheet Tutorials.
- Excel VBA Protect Sheet Without Password in 2 Easy Steps: Click here to open.
- Excel VBA Unprotect Sheet Without Password in 2 Easy Steps: Click here to open.
- Excel VBA Unprotect Sheet with Password in 2 Easy Steps: Click here to open.
- Excel VBA Protect Sheet Allow Filter in 2 Easy Steps: Click here to open.
- Excel VBA Protect Sheet Allow Select Locked Cells in 4 Easy Steps: Click here to open.
You can find more Excel and VBA Tutorials in the organized Tutorials Archive: Click here to visit the Archives.
If you want to learn how to automate Excel (and save time) by working with macros and VBA, you may be interested in the following Premium Excel Macro and VBA Training Materials:
- Premium Courses at the Power Spreadsheets Academy: Click here to open.
- Books at the Power Spreadsheets Library: Click here to open.
- VBA Cheat Sheets: Click here to open.
If you want to save time when working with macros and VBA, you may be interested in AutoMacro: Click here to learn more about AutoMacro (affiliate link). AutoMacro is an add-in for VBA that installs directly into the VBE. Depending on the version, AutoMacro comes loaded with:
- Code generators.
- An extensive code library.
- The ability to create your own code library.
- Advanced coding tools.
If you need consulting services, you may want to consider working with ExcelRescue. ExcelRescue is my usual suggestion for people who (like you) may need help with Excel tasks/projects: Click here to visit ExcelRescue (affiliate link).
The VBA Protect Sheet with Password Snippet Template/Structure
The following is the VBA protect sheet with password snippet template/structure I explain (step-by-step) in the Sections below.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-protect-sheet-password/ 'Sheet is a worksheet WorkbookObjectReference.WorksheetObjectReference.Protect Password:="SheetPassword" 'Sheet is a chart sheet WorkbookObjectReference.ChartObjectReference.Protect Password:="SheetPassword"
This Excel VBA Protect Sheet with Password Tutorial is accompanied by an Excel workbook with the data and VBA code I use when describing the step-by-step process below. Get this example workbook (for free) by clicking the button below.
The VBA code in the Excel workbook that accompanies this Excel VBA Protect Sheet with Password Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section above.
The example workbook has a single (empty) worksheet.
- The name of the example worksheet is “Protect Sheet with Password”.
- This is the sheet the VBA protect sheet with password example macro I create (by following the step-by-step process below) works with. In other words: The VBA protect sheet with password example macro protects this sheet with a password.
The image below displays the example worksheet before I execute the VBA protect sheet with password example macro.
Notice the Protect Sheet button (inside the Protect group of commands) in the Excel Ribbon (indicating the example worksheet isn’t (currently) protected).
Step 1: Refer to Sheet
Refer to the sheet you want to protect with password.
In other words: Create a VBA expression that returns an object representing the applicable sheet (you want to protect with password). As a general rule: Work with 1 of the following objects:
- A Worksheet object, representing a worksheet.
- A Chart object, representing a chart sheet.
Consider explicitly including the following references to create a fully qualified object reference returning the applicable Worksheet (representing a worksheet) or Chart (representing a chart sheet) object:
- A reference to the applicable workbook. The following VBA constructs (among others) may return a Workbook object:
- The Application.ThisWorkbook property.
- The Application.Workbooks and Workbooks.Item properties.
- The Application.ActiveWorkbook property.
- A reference to the applicable worksheet or chart sheet. The following VBA constructs (among others) may return a Worksheet or Chart object:
- The Workbook.Sheets and Sheets.Item properties.
- The Workbook.Worksheets and Worksheets.Item properties.
- The Workbook.Charts and Charts.Item properties.
- The Application.ActiveSheet property.
- The Workbook.ActiveChart property.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-protect-sheet-password/ 'Sheet is a worksheet WorkbookObjectReference.WorksheetObjectReference 'Sheet is a chart sheet WorkbookObjectReference.ChartObjectReference
Step 1 Example
I:
- Refer to the worksheet named “Protect Sheet with Password” inside the workbook where the procedure is stored.
- Work with the following VBA constructs to obtain a Worksheet object representing this worksheet:
- The Application.ThisWorkbook property: ThisWorkbook.
- The Workbook.Worksheets and Worksheets.Item properties: Worksheets(“Protect Sheet with Password”).
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-protect-sheet-password/ ThisWorkbook.Worksheets("Protect Sheet with Password")
Step 2: Protect Sheet and Specify Password
Do the following to:
- Protect the sheet (you refer to in step #1); and
- Specify the protection password.
(1) Start with the Worksheet or Chart object reference you created in step #1.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-protect-sheet-password/ 'Sheet is a worksheet WorkbookObjectReference.WorksheetObjectReference 'Sheet is a chart sheet WorkbookObjectReference.ChartObjectReference
(2) Call the applicable version of the Protect method:
- Worksheet.Protect, if protecting a worksheet.
- Chart.Protect, if protecting a chart sheet.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-protect-sheet-password/ 'Sheet is a worksheet WorkbookObjectReference.WorksheetObjectReference.Protect 'Sheet is a chart sheet WorkbookObjectReference.ChartObjectReference.Protect
(3) Use the Password parameter of the Protect method to specify the protection password.
- Specify the password as a string.
- The password you specify is case sensitive.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-protect-sheet-password/ 'Sheet is a worksheet WorkbookObjectReference.WorksheetObjectReference.Protect Password:="SheetPassword" 'Sheet is a chart sheet WorkbookObjectReference.ChartObjectReference.Protect Password:="SheetPassword"
Step 2 Example
I do the following:
(1) Start with the Worksheet object reference I created in step #1.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-protect-sheet-password/ ThisWorkbook.Worksheets("Protect Sheet with Password")
(2) Call the Worksheet.Protect method.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-protect-sheet-password/ ThisWorkbook.Worksheets("Protect Sheet with Password").Protect
(3) Use the Password parameter of the Worksheet.Protect method to specify the protection password as “Protect Sheet with Password”.
'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-protect-sheet-password/ ThisWorkbook.Worksheets("Protect Sheet with Password").Protect Password:="Protect Sheet with Password"
The full VBA protect sheet with password example macro is as follows:
Sub ProtectSheetPassword() 'Source: https://powerspreadsheets.com/ 'More information: https://powerspreadsheets.com/vba-protect-sheet-password/ 'Do the following: 'Step 1: Refer to the "Protect Sheet with Password" worksheet in this workbook 'Step 2: Protect the worksheet with the password "Protect Sheet with Password" ThisWorkbook.Worksheets("Protect Sheet with Password").Protect Password:="Protect Sheet with Password" End Sub
The GIF below illustrates the effects of using the VBA protect sheet with password example macro.
Notice how:
- The Protect Sheet button (inside the Protect group of commands) in the Excel Ribbon (indicating the example worksheet isn’t (currently) protected);
- Is replaced by the Unprotect Sheet button (indicating the example worksheet is now protected) when I execute the VBA protect sheet with password example macro.
Download the VBA Protect Sheet with Password Example Workbook
This Excel VBA Protect Sheet with Password Tutorial is accompanied by an Excel workbook with the data and VBA code I use when describing the step-by-step process above. Get this example workbook (for free) by clicking the button below.
The VBA code in the Excel workbook that accompanies this Excel VBA Protect Sheet with Password Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section above.
The following Excel Macro and VBA Tutorials may help you better understand and implement the contents above.
- Tutorials about general macro and VBA constructs and structures:
- Tutorials for Beginners:
- Excel Macros: Click here to open.
- Excel VBA: Click here to open.
- Enable macros in Excel: Click here to open.
- Work with the Visual Basic Editor (VBE): Click here to open.
- Create Sub procedures: Click here to open.
- Refer to objects (click here to open), including sheets (click here to open).
- Work with:
- Methods: Click here to open.
- Data types: Click here to open.
- Loops: Click here to open.
- Tutorials for Beginners:
- Tutorials with practical VBA applications and macro examples:
- Activate workbook: Click here to open.
- Create new workbook: Click here to open.
- Open workbook: Click here to open.
- Delete sheet: Click here to open.
This Excel VBA Protect Sheet with Password Tutorial is part of a more comprehensive series of Excel VBA Protect or Unprotect Sheet Tutorials.
- Excel VBA Protect Sheet Without Password in 2 Easy Steps: Click here to open.
- Excel VBA Unprotect Sheet Without Password in 2 Easy Steps: Click here to open.
- Excel VBA Unprotect Sheet with Password in 2 Easy Steps: Click here to open.
- Excel VBA Protect Sheet Allow Filter in 2 Easy Steps: Click here to open.
- Excel VBA Protect Sheet Allow Select Locked Cells in 4 Easy Steps: Click here to open.
You can find more Excel and VBA Tutorials in the organized Tutorials Archive: Click here to visit the Archives.
If you want to learn how to automate Excel (and save time) by working with macros and VBA, you may be interested in the following Premium Excel Macro and VBA Training Materials:
- Premium Courses at the Power Spreadsheets Academy: Click here to open.
- Books at the Power Spreadsheets Library: Click here to open.
- VBA Cheat Sheets: Click here to open.
If you want to save time when working with macros and VBA, you may be interested in AutoMacro: Click here to learn more about AutoMacro (affiliate link). AutoMacro is an add-in for VBA that installs directly into the VBE. Depending on the version, AutoMacro comes loaded with:
- Code generators.
- An extensive code library.
- The ability to create your own code library.
- Advanced coding tools.
If you need consulting services, you may want to consider working with ExcelRescue. ExcelRescue is my usual suggestion for people who (like you) may need help with Excel tasks/projects: Click here to visit ExcelRescue (affiliate link).