Забыл пароль от vba excel

Установка пароля на VBA-проект и снятие защиты с него. Отключение забытого пароля с проекта VBA, созданного в книге Excel с расширением .xlsm.

Защита проекта VBA паролем помогает от случайного или намеренного изменения кода обычным пользователем. От злоумышленников простая установка пароля не спасет.

Защита проекта VBA стандартными средствами:

  1. Перейдите в окно «VBAProject — Project Properties» через пункты меню: «Tools» >> «VBAProject Properties».
  2. В открывшемся окне выберите вкладку «Protection» и установите галочку в чек-боксе «Lock project for viewing».
  3. Введите пароль в поле «Password» и повторите пароль в поле «Confirm password».

Окно «VBAProject - Project Properties»

  1. Нажмите кнопку «OK» и закройте книгу Excel.

При следующем открытии этой книги проект VBA будет защищен.

Снятие защиты с VBA-проекта

Снятие защиты с проекта VBA стандартными средствами:

  1. Перейдите в окно «VBAProject — Project Properties» через пункты меню: «Tools» >> «VBAProject Properties».
  2. В открывшемся окне выберите вкладку «Protection» и уберите галочку из чек-бокса «Lock project for viewing».
  3. Очистите поля «Password» и «Confirm password».
  4. Нажмите кнопку «OK» и закройте книгу Excel.

При следующем открытии этой книги проект VBA будет доступен.

Отключение забытого пароля

Этот способ отключения забытого пароля применим к файлам Excel с расширением .xlsm. Чтобы не забывать пароли, используйте менеджер KeePass.

  1. Сделайте копию книги Excel, чтобы случайно не потерять ее при вмешательстве в код.
  2. Откройте файл .xlsm любым архиватором (я использую бесплатный 7-Zip). Иногда рекомендуют заменить расширение .xlsm на .zip или добавить одно к другому (.xlsm.zip), но делать этого совершенно не обязательно.

  1. Откройте в архиве папку «xl», найдите файл «vbaProject.bin» и перетащите его в папку с книгой Excel (по умолчанию происходит копирование).

  1. Откройте файл «vbaProject.bin» программой «Notepad++», обычный блокнот не подойдет.
  2. С помощью поиска (Ctrl+F) найдите фразу DPB=, замените в ней букву «B» на любую другую, например на «z» и сохраните файл.

  1. Перетащите файл «vbaProject.bin» обратно в архив, подтвердив копирование. Архив можно закрыть.
  2. Откройте книгу Excel и на запрос о продолжении загрузки с невалидным ключом «DPz» ответьте «Да».

  1. Откройте редактор VBA, дважды или трижды нажав «OK» в сообщении о неизвестной ошибке (у меня такое предупреждение появляется трижды).

  1. Сохраните книгу Excel и закройте.
  2. Откройте файл Excel, перейдите в редактор VBA, откройте окно «VBAProject — Project Properties» («Tools» >> «VBAProject Properties») и убедитесь, что галочка у чек-бокса «Lock project for viewing» снята, поля «Password» и «Confirm password» — пустые.

How can I programmatically remove a (known) password from an Excel VBA project?

To be clear: I want to remove the password from the VBA Project, not the workbook or any worksheets.

braX's user avatar

braX

11.5k5 gold badges20 silver badges33 bronze badges

asked Nov 7, 2008 at 15:48

Barry-Jon's user avatar

5

Another way to remove VBA project password is;

  • Open xls file with a hex editor.
    (ie. Hex Edit http://www.hexedit.com/)
  • Search for DPB
  • Replace DPB to DPx
  • Save file.
  • Open file in Excel.
  • Click «Yes» if you get any message box.
  • Set new password from VBA Project Properties.
  • Close and open again file, then type your new password to unprotect.

UPDATE: For Excel 2010 (Works for MS Office Pro Plus 2010 [14.0.6023.1000 64bit]),

  • Open the XLSX file with 7zip

If workbook is protected:

  • Browse the folder xl
  • If the workbook is protected, right click workbook.xml and select Edit
  • Find the portion <workbookProtection workbookPassword="XXXX" lockStructure="1"/> (XXXX is your encrypted password)
  • Remove XXXX part. (ie. <workbookProtection workbookPassword="" lockStructure="1"/>)
  • Save the file.
  • When 7zip asks you to update the archive, say Yes.
  • Close 7zip and re-open your XLSX.
  • Click Protect Workbook on Review tab.
  • Optional: Save your file.

If worksheets are protected:

  • Browse to xl/worksheets/ folder.
  • Right click the Sheet1.xml, sheet2.xml, etc and select Edit.
  • Find the portion <sheetProtection password="XXXX" sheet="1" objects="1" scenarios="1" />
  • Remove the encrypted password (ie. <sheetProtection password="" sheet="1" objects="1" scenarios="1" />)
  • Save the file.
  • When 7zip asks you to update the archive, say Yes.
  • Close 7zip and re-open your XLSX.
  • Click Unprotect Sheet on Review tab.
  • Optional: Save your file.

answered Oct 20, 2011 at 12:23

Uygar Y's user avatar

Uygar YUygar Y

1,9621 gold badge12 silver badges16 bronze badges

11

I found another way to solve this one to avoid password of VBA Project, without losing password.

If the file type is XLSM files:

  1. Rename the .xlsm as .zip (or you can open the .xlsm with 7zip/WinRAR) and open/extract it
  2. Edit the xl/vbaProject.bin file with Notepad++ or HexEdit
  3. Search for DPB= and replace it with DPx=

enter image description here

  1. Save the file
  2. Copy this file back into the .zip (or zip the files back up)
  3. Rename the archive back to .xlsm
  4. Open the file in Excel, if prompted to «Continue Loading Project», click Yes. If prompted with errors, click OK. Note: the code may still be blank or corrupted, which we fix in the next step
  5. Save the file as a new .xlsm file
  6. Open the new file in Excel (should be no errors now)
  7. Press Alt+ F11 to open the VBA editor

or

Follow this Step Also

I found another way to solve this one to avoid password of VBA Project, without losing excel password.
use Hex-editor XVI32 for the process

if the file type is XLSM files:

  1. Open the XLSM file with 7-Zip (right click -> 7-Zip -> Open archive). 2. Copy the xl/vbaProject.bin file out of the file (you can drag and drop from 7-Zip), don’t close 7-Zip

  2. Open the vbaProject.bin file with HexEdit

  3. Search for «DPB=» and replace it with «DPx=»

  4. Save the file

  5. Copy this file back into 7-Zip (again, drag and drop works)

  6. Open the XLSX file in Excel, if prompted to «Continue Loading Project», click Yes. If prompted with errors, click OK. 8. Press Alt+ F11 to open the VBA editor.

  7. While press it will show error “Unexpected error (40230)”, just click OK (6 or 7 times) until it goes away.

  8. Then it will open Automatically

answered Jan 24, 2018 at 6:15

Thomas's user avatar

ThomasThomas

1,42514 silver badges30 bronze badges

3

This has a simple method using SendKeys to unprotect the VBA project. This would get you into the project, so you’d have to continue on using SendKeys to figure out a way to remove the password protection:
http://www.pcreview.co.uk/forums/thread-989191.php

And here’s one that uses a more advanced, somewhat more reliable method for unprotecting. Again, it will only unlock the VB project for you.
http://www.ozgrid.com/forum/showthread.php?t=13006&page=2

I haven’t tried either method, but this may save you some time if it’s what you need to do…

answered Nov 7, 2008 at 16:44

Jon Fournier's user avatar

Jon FournierJon Fournier

4,2493 gold badges32 silver badges43 bronze badges

3

My 2 cents on Excel 2016:

  1. open the xls file with Notepad++
  2. Search for DPB= and replace it with DPx=
  3. Save the file
  4. Open the file, open the VB Editor, open modules will not work (error 40230)
  5. Save the file as xlsm
  6. It works

answered Aug 25, 2020 at 14:47

Timo's user avatar

TimoTimo

2,8463 gold badges29 silver badges27 bronze badges

I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.

This one does not use SendKeys.

Let me know if this helps!
JFV

answered Nov 7, 2008 at 16:40

JFV's user avatar

JFVJFV

1,8036 gold badges24 silver badges36 bronze badges

After opening xlsm file with 7 zip, extracting vbaproject.bin and in Notepad ++ replacing DpB with DPx and re-saving I got a Lot of vbaproject errors and vba project password was gone but no code/forms.

I right clicked to export and was able to re-import to a new project.

geisterfurz007's user avatar

answered Sep 12, 2019 at 11:35

Aveesh's user avatar

AveeshAveesh

651 gold badge2 silver badges6 bronze badges

1

Время на прочтение
2 мин

Количество просмотров 17K

Здравствуйте, друзья!
Последние дни бился над такой задачей:
Имеется файл .xls, в нем макрос на VBA, защищенный паролем. Файл создается путем экспортирования из программы ГрандСмета и содержит в себе смету, которая должна обрабатываться макросом.
На 32х разрядных версиях — отрабатывает без проблем.

На 64х столкнулся со следующей ошибкой:

Справка Microsoft дает однозначный ответ:

Связывался с Тех.Поддержкой, объяснял причину. Ответ был один:

У нас все работает. Проверяли на 64х разрядных версиях.

Тогда я решился самостоятельно править код макроса. Сложность, с которой столкнулся — модуль защищен паролем. О том, как сбросить/изменить пароль не используя специализированное ПО для взлома пароля
Итак, приступим. Заранее предупрежу — я не профессиональный программист, а скорее ЭниКейщик, так что возможны некорректные формулировки, а кому-то может и вовсе не понравиться выбранный мной путь.
Первым делом я стал бороздить просторы Сети в поисках решения. В основном полным-полно ссылок на ПО, из разряда PasswordCracker. Одно из решений опубликованное на Ru-Board’e полностью удаляло код модуля VBA.
В конце концов, мои старания вознаградились — предлагаю Вам вольный перевод найденного решения (к сожалению не могу указать первоисточник — не помню) + попытка понять суть выявленной «уязвимости».

Думаю, что ни для кого не секрет, что начиная с Excel 2007 использует Microsoft Office Open XML в качестве своего основного формата.

FarManager превосходно открывает xls файл с отображением всей структуры документа.
1. Запускаем FarManager.
2. Открываем файл для редактирования.
3. Ищем строку с определением ключа DPB, и изменяем имя ключа на DPW.
4. Сохраняем.
4. Открываем файл в Excel.
5. Подтверждаем загрузку проекта, не смотря на некорректный ключ (который мы сами и сделали некорректным в п.3):

6. В окнах с сообщениями об ошибке смело жмем ОК.
7. С помощью комбинации Alt+F11 — запускаем VBA Editor и, вуаля, код макроса доступен для редактирования.

Теперь причина возникавшей ошибки при запуске макроса в среде x64 — очевидна!

Компилятор подсказывает о том, что код в данном проекте должен быть обновлен для использования на 64х разрядных системах, конкретно указав, что надо было всего лишь добавить ключевое слово PtrSafe при объявлении функции.

Изменения внес, пересохранил, проверил. Все работает. Порадовал коллег решением наболевшей проблемы + приобрел опыт.

Пытаюсь решить последний вопрос, на котором я и застопорился:
Как вразумительно, и не обидев, объяснить Тех.Поддержке о решении возникшей проблемы с запуском макроса? Не должен же я самостоятельно перелапачивать все шаблоны (а их порядка 50), чтобы макрос корректно отрабатывал на x64 версиях Офиса. К тому же вопрос этики — пришлось «обходить» защиту кода макроса.

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

P.S. Вдохновленный решением возникшей проблемы, и оставшись только с одним вопросом, который задал чуть выше, я решился создать свой первый топик на Хабре, в надежде на профессиональный дружеский совет.

Вы должны сначала понять значение VBA, прежде чем искать решения для взлома пароля VBA в Excel.

Visual Basic для приложений (VBA) — это аббревиатура от Visual Basic для приложений. Он используется в различных продуктах Microsoft, в частности в MS Excel, для внедрения новых функций и автоматизации общих процессов. Большинство пользователей шифруют программы VBA с помощью паролей из-за их природы и необходимости защиты файлов. С другой стороны, пароли VBA не являются безошибочными, и их можно забыть. Очевидно, вы не сможете получить доступ к своим программам Excel VBA или изменить их. Вам понадобится методика взлома пароля Excel VBA, чтобы остановить хаос.

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

1. Измените расширение файла, чтобы взломать пароль VBA в Excel.

Эта процедура влечет за собой преобразование расширения файла .xlsm в другой формат и последующее его получение в формате .xlsm. Хотя процедура обширна, вы можете в конечном итоге взломать пароль VBA в Excel, внимательно следя за ней. Просто изменив расширение файла, следующие шаги демонстрируют, как сбросить пароль VBA в Excel.

  • Найди свой target.xlsm файл и замените расширение .xlsm с .zip.
  • Используйте любой из Программы-архиваторы вы должны открыть этот файл. WinRAR или 7-Zip есть два варианта. Если вы это сделаете, вы должны увидеть следующую структуру своего файлового каталога.
  • Выберите Каталог XL вариант и извлеките файл с именем «VBAProject.bin».
  • В любом шестнадцатеричном редакторе откройте VBAProject.bin файл и найдите «DPB =» текст внутри файла.
  • Просто сотрите этот текст и замените его на «DPX =» как только вы его нашли. Теперь сохраните и закройте файл шестнадцатеричного редактора. Заменить старый VBAProject.bin с новый VBAProject.bin это было отредактировано шестнадцатеричным способом.
  • Переименуйте файл в .xlsm а затем откройте его в Excel. Выбирать «Да» из всплывающего окна с предупреждением и не обращайте внимания на другие параметры.
  • Если появится диалоговое окно, запустите Редактор VBA и выберите «OK»
  • Выбирать характеристики из контекстного меню, когда вы щелкаете правой кнопкой мыши имя вашего Проект VBA. Удалите все существующие пароли, перейдя в «Защита» страница. Также отключите и включите «Заблокировать проект для просмотра» коробка. Введите и подтвердите приемлемый пароль. Чтобы внести изменения, нажмите «Ok. »

2. Сброс пароля VBA в Excel с помощью редактора Visual Basic

Редактор Visual Basic, в отличие от шестнадцатеричного редактора, позволяет пользователям изменять коды символов, а не шестнадцатеричные значения. Процедура не требует больших затрат времени. Однако вы должны проявлять осторожность, потому что коды требуют пристального внимания во избежание ошибок. Приведенные ниже методы демонстрируют, как обойти пароль проекта VBA в Excel с помощью редактора Visual Basic.

  • Для начала откройте Рабочая тетрадь, который содержит все защищенные листы.
  • Чтобы запустить или проверить редактор Visual Basic, используйте Alt + F11. Затем в правом углу окна введите Вставить модуль и вставьте следующий код.
  • Закройте Редактор VB окно и перейдите к листу, с которого хотите снять защиту.
  • Дважды щелкните значок взломщик паролей в предложенном списке после ввода Tools-Macro-Macros.

3. Измените пароль VBA в Excel с помощью шестнадцатеричного редактора.

Hex Editor предоставляет вам хорошую платформу для редактирования шестнадцатеричных данных, позволяя наконец решить проблему взлома пароля в VBA для Excel. Создайте фиктивный xls-файл, установите пароль и затем используйте его для доступа к защищенному Excel с помощью этого метода.

  • Сделать новый файл Excel, использовать Шестнадцатеричный редактор (xls). Достаточно простого файла.
  • Под Раздел VBA, создайте пароль для этого файла. Вы можете перейти к этой опции, нажав Alt + F11.
  • Сохранить а также оставлять этот новый файл после того, как вы создали памятный пароль.
  • Открыть свежеприготовленный файл снова, но на этот раз с шестнадцатеричный редактор. Найдите и скопируйте строки, начинающиеся со следующих ключей: CMG =, DPB =, а также GC = после того, как файл был открыт.
  • Теперь, используя Шестнадцатеричный редактор, откройте файл электронной таблицы, в котором вы хотите расшифровать пароль. Копировать скопированные тексты и вставить их в соответствующие поля перед сохранением модификации. Закройте файл.
  • Чтобы увидеть Код VBA, откройте файл Excel и войдите в систему, используя тот же пароль вы использовали для манекена xls файл.

Автоматизированное решение

Если указанные выше процедуры не работают, пользователи могут обратиться за помощью к автоматизированному решению. В Средство восстановления паролей файлов DataHelp VBA одно из таких приложений. Он предназначен для восстановления паролей к файлам VBA, которые были потеряны или забыты, без потери данных. Он также поддерживает такие типы файлов MS Office, как .xls, .xlsx, .doc, .mdb и .dot. Самым приятным аспектом этого инструмента является то, что он удаляет старые пароли и заменяет их новыми паролями проекта VBA. Он имеет удобный интерфейс, и для его использования не требуются технические знания.

1. Запустить программное обеспечение и выбрать Проект VBA с помощью Добавить файлы) или Добавить папку кнопка.

Домашняя страница для взлома пароля VBA в Excel

2. Как показано на изображении, найти в VBA файл на вашем ПК.

найдите файл VBA в вашей системе

3. Рассмотрение файлы, которые вы добавили, а затем щелкните Параметр сброса.

Параметр сброса для взлома пароля VBA в Excel

4. Когда процесс заканчивается, инструмент отобразит пароль.

После завершения процесса инструмент отображает пароль

Заключительные слова

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

For older .XLS files:

  1. Open file in any hex editor

  2. Search for the text «DPB=» (no quotes, you should find it just above «[Host Extender Info]»

    1

  3. Change it to «DPx=«, save and close the file

    2

  4. Open the file in Excel and press Yes if the following warning pops up:

    3

  5. Open the VBA editor (Alt+F11) and press OK whenever the following warning pops up:

    4

  6. Right-click the VBA project name, select Properties, go to the Protection tab and delete the existing passwords as well as uncheck the Lock project for viewing checkbox:

    5

  7. Re-check the Lock project for viewing checkbox and add your own memorable password.

  8. OK your way out and now the VBA code is accessible!

For newer .XLSM files:

  1. Change the file’s extension to .ZIP

  2. Open the file in any archiver such as WinRAR or 7-Zip and you’ll see the following directory structure:

    6

  3. Go into the xl directory and extract vbaProject.bin:

    7

  4. Perform steps #1-3 above (from the For older .XLS files section) with vbaProject.bin

  5. Replace the old vbaProject.bin in the ZIP file with the new hex edited version

  6. Change the file’s extension back to .XLSM

  7. Perform steps #4-7 above

Community's user avatar

answered Sep 7, 2014 at 0:53

Karan's user avatar

KaranKaran

55.6k20 gold badges117 silver badges189 bronze badges

7

How to Crack Excel VBA Password

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.

Need to Supply Password to View 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”.

Enable Reset VBA password – a in Excel

Step 2. Select an option to reset the password—here we may select “Unprotect all sheets in active workbook” from the menu.

Select Unprotect all sheets in active workbook in VBA Password Reset a

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.

SysTools VBA Password Remover Check for Prerequisites Page

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.

Add VBA Password Protected File to SysTools VBA Password Remover

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.

VBA Password Has Been Reset with SysTools VBA Password Remover

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.

Change Excel VBA File Extension from XLSM to ZIP

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.

Uncheck Hide Extensions for Known File Types in Windows Folder Options

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.

Find vbaProject.bin File in xl Folder

Step 4. Open the “vbaProject.bin” file with a hex editor such as HxD.

Step 5. Look for “DPB” within the file.

Open vbaProject.bin and Search for DPB in HxD Hex Editor

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.

Change DPB to DPx with HxD Hex Editor

Step 7. Compress all the folders and files to a ZIP.

Compress the Modified XLSM Folders and Files to a ZIP File

Step 8. Change the extension from “zip” to “xlsm”, and then opening it.

Change Extension from ZIP to XLSM

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”.

Uncheck "Lock project for viewing" for Viewing the Cracked VBA Code

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.

Photo of Susanna

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.

Stuck with an Excel VBA document that’s locked with a password? We’ll show you how to remove the password protection to recover the contents of the VBA macro.

Stuck with a VBA document that’s password protected? Here’s how to pick the lock.

It’s not unusual to take ownership of someone else’s Excel document, especially in the workplace. Usually, the transition goes smoothly — but there are pitfalls that can cause some real headaches.

For instance, six months down the line you might try edit one of the VBA macros that’s integral to the spreadsheet, only to find that it’s password protected. What happens now? Well, with a bit of tinkering behind the scenes, it’s not too difficult to remove that protection entirely.

Here’s how to eliminate password protection from a VBA document in Excel. It might just make you think twice about how secure your spreadsheets really are.

How to Set Up a Password

If you need to crack a password, you may already be aware how to set one up. However, it’s still worth laying out how this kind of protection works.

Head to the Developer tab in Excel and click Macros.

excel macros

In case you don’t see the Developer tab, go to File > Options and then Customize Ribbon. Now move the Developer command group from the left pane over to the right.

excel vba

Once you selected Macros in the Developer tab, enter a name for your macro (it’s just an example, so the specifics don’t matter) and then click Create.

protected excel macro

Copy and paste the following code into the Visual Basic Editor. This is a simple macro that will enter the quoted text into cell A1. It serves no real purpose, but we need something to protect with a password.

  Range("A1").Value = "Password Protected" 

You should end up with something that looks like this.

excel password code

In the Visual Basic Editor, navigate to Tools > VBAProject Properties.

vba project properties

Head to the Protection tab and you’ll be able to set a password. You’ll also need to check the box labeled Lock project for viewing.

excel password properties

Click OK, make sure to save your Excel document as an XLSM file, and we can test out whether our password works. Close your document and reopen it, then head to the Developer tab and click Visual Basic.

excel password prompt

When you try to access the relevant VBAProject, you’ll see a password prompt. Now we can figure out how to remove this kind of protection.

How to Remove a Password

Now for the difficult part, although it’s really quite straightforward once you know what you’re doing. First, we’re going to need to download a hex editor. If you don’t have one already, HxD is a good free option, but there are plenty of alternatives available.

Our process differs slightly depending on whether we’re cracking a password in an older XLS file or a newer XLSM file. If you’re working with the former, feel free to skip the next section.

Preparing Our XLSM File

We need to perform a little extra preparatory work to remove a password from an XLSM file. Find it on your hard drive, then rename it, adding .zip onto the end.

Next, open it with archive compression software like WinRAR or 7-Zip. You should find a folder labelled xl.

excel xl folder

Inside this folder, you’re looking for a file with the name vbaProject.bin.

vba project properties

Extract this file and open it with your Hex Editor.

Disabling the Password

Here’s where being able to set up a password comes in handy. Create a dummy Excel document, add a macro into it, and set a password as described at the beginning of this article. Next, we’re going to take the Hex code that stipulates what the password is, and we’ll insert it into the file we want to access.

Once you have that file set up, save it and perform the same process we did a minute ago so that you end up with another vbaProject.bin file. Make sure to remember the password!

You should now have both of your vbaProject.bin files open in your Hex Editor. Don’t get them mixed up or we’re going to have big problems.

Use Ctrl + F in the file you created to find the following string:

  CMG= 

This is the start of the code that stipulates the current password. We need to copy and paste three values:

  CMG=DPB=GC= 

Below you can see how I did it.

excel copy code

Transfer this code over to your other vbaProject.bin file, and place it in the corresponding position, making sure not to delete anything else. Save your edited hex file.

Now, delete the original vbaProject.bin file from the document we’re trying to remove the protections from. Replace it with your edited vbaProject.bin file, then change its filename back from .zip to .xlms or .xls.

Open up the file in Excel. Head to the Developer tab and click Visual Basic, and try to access the Project menu. You should see the password prompt, and with any luck, the correct password should be the one we set up in our dummy document.

excel new password

We’re back in the document! Now you can get along with whatever you were meant to be doing.

Notes on Beating the System

This trick can be very handy when you’re in a bind, and you desperately need access to a password protected VBA macro. However, it should also illustrate a major security flaw that’s present in Excel.

If you’re using this kind of password protection to defend your VBA code, know that a workaround is out there. It’s a deterrent at best — anyone with the ability to run a Google search will know exactly how to cut through your defenses.

It just goes to show how important it is for us to constantly question our security practices. Applying password protection might seem to offer valuable piece of mind, but in a situation like this one, it’s not all that effective.

Do you have questions about removing password protection from an Excel document? Or do you have a security tip you want to share with others? Why not join the conversation in the comments section below?

Image Credit: OrelPhoto via Shutterstock.com

Понравилась статья? Поделить с друзьями:
  • Забыл пароль от microsoft word
  • Забыл пароль от excel 2007
  • Забыл пароль на excel документ
  • Забыл пароль на excel 2016
  • Забыл пароль к документу excel