Vba excel project locked

Время на прочтение
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 должен быть доступен.

8)       Но иногда защита не снимается, тогда нужно сохранить файл, проверить, что он действительно сохранился! И проделать повторно операции с 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. Так и снимаются без особых проблем.

Установка пароля на 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» — пустые.

Probably experienced a sad situation when the password for your Excel workbook is lost or forgotten.  Head up, because it’s not the end of the world. Nowadays we can easily break down the forgotten password and recover our hidden VBA project in at least a few ways.
From these many ways, there are major 2 ways of breaking the MS Excel password both for the workbook only and the VBA project:
– using the VBA code
– unpacking the Excel file and changing the existing XML code manually.

I am going to focus on this second option, which I guess wasn’t fully explained in the one piece so far.

There are a lot of sources on the Web trying to show step-by-step how to unlock the Excel document, but I couldn’t find any with a detailed explanation including these 2 situations, which this article is about. Let’s get started then.

First of all, I would like to show the MS Excel workbook’s essence.  The Excel document, which we know contains a multitude of cells, is located in columns and rows. Moreover, our workbook can be expanded by a various number of worksheets, between which we can smoothly migrate afterward.  Probably you didn’t wonder before why the excel document looks like this is it really one file, or do we have another feature behind it? All these things will be clarified as you continue to read this article.

Excel typical document

Pic. 1 Typical MS Excel document is built from the bulk of cells placed in rows and columns. Every single worksheet looks the same at the initial stage. The file can be expanded without limitation.

You don’t need to care about it really when everything is fine with your document, i.e. it’s not locked or at least you know the password. Checking the workbook protection is a simple thing, You must select the “File” in the main toolbar (top left) and go to the “Info” section, where you will see all protected sheets (or workbook) in the yellow label (Pic. 2).

Excel info sheets protection

Pic. 2 The list of worksheets protected in Excel, which is labeled in yellow.

Excel whole workbook protection

Pic. 3 Excel 2016 – protection of the whole workbook.

If your VBA project is locked, you won’t access it at all. After the double-click, the console will ask you about the password (Pic. 4).

Excel VBA project locked

Pic. 4 VBA project in Excel 2016 locked.

This is all, I wanted to say about the Excel workbook and the VBA project protection. If your password is unknown without any reason, then you must break it if some alterations within the workbook are needed.

The option, which I would like to explain in detail is unpacking (unzipping) the Excel document. Here we are heading to the explanation, of what the Excel document is built from.
The essential software, which you will need for this purpose is the 7Zip program. It’s quite similar to WinZip or WinRar. This application allows us to open the zipped GIS files with i.e. .kmz extension, like here.  In this event, we should do the right click on our Excel document, next select the 7Zip and “Open archive” option (Pic. 5).

Excel opening in 7zip

Pic. 5 Opening the Excel file in the 7Zip application.

As you can see, the 7Zip application works pretty much the same as WinZip mentioned above. Another thing, which brings us an answer about the essence of the Excel workbook is, that our file is built from many other minor files. They are mostly .xml files comprising of our spreadsheets and data included (Pic. 6).

Excel .xml structure opened in 7Zip

Pic. 6 The structure of the MS Excel workbook previewed via 7Zip software with the random directory opened.

Now every file can be opened at least in the standard Notepad application. In our case, the most important files to open are based in the /xl/ folder (Pic.7), where we have basically all that has been included in our visual Excel workbook. Now we can see it in separate  .xml files (Pic. 6).

Excel xl folder displayed in 7Zip software

Pic. 7 The /xl/ folder includes all elements present in our Workbook (charts, images, calculations, etc). In order to break the password, we must take a look at the /worksheets/ subfolder and workbook.xls file.

If we want to remove the password, we must look at the /worksheets/ subfolder or workbook.xml file. It depends on our workbook information. If we have a few sheets locked only, then we must enter the aforementioned folder. If our whole workbook has been locked, then we must open the file.
Firstly let’s see how to deal with the separate sheets. When you open the /worksheets/ directory, you will see the list of all sheets available in your workbook (Pic. 8).

Excel worksheets 7Zip xml

Pic. 7 The list of all worksheets available in the given workbook is previewed in the 7Zip software.

Now we can open any of it with the mouse right-click (Pic. 8). The tool will use Notepad as the default editor (Pic. 9).

Excel spreadsheet worksheets opened

Pic. 8 Opening the .xml Excel sheet via 7Zip and right-click.

Excel .xml sheet opened

Pic. 9 One of the worksheet opened as the .xml file in the Notepad application.

The XML code above doesn’t look friendly. We can obviously find a way forward to display it tidier, however, we don’t need to do it necessarily.
The Notepad app is enough for the changes, which we desire. Once you’ve opened the worksheet file, click the Ctrl+F and find the “Protection” string inside the code (Pic. 10). If you will do so, then select it gently down to the bracket, which appears to finish the section. When you selected it, just press the Backspace button and save the document. Your sheet should be already unprotected.

Excel sheet unprotection

Pic. 10 Easy way for sheet unprotection in Excel.

Repeat this task for all the sheets, which are protected. It may be hard to determine which sheet exactly is protected when we are based on the yellow-labeled list in our file information (Pic. 2). In this event, I would advise you to jump into the VBA console, where you will see the sheet number next to the name (Pic. 11).

Excel VBA list of sheets

Pic. 11 List of worksheets with their original order in the VBA Excel console.

If your VBA project is locked, then the only option available is to due to the SHEET function. The short formula will bring you the answer shortly (Pic. 12).

Excel sheet number and VBA project list

Pic. 11 Determination of the worksheet number in our Excel workbook in comparison with the VBA project worksheet list.

If we are knowing the sheet number is easier for us to pick up the .xml file and do the relevant alterations.
Again, Notepad doesn’t display our XML code in a smart way. However, there is no other option to launch the .xml file, unless we extract it outside the main Excel file and open it in different applications or browsers. This is not the primary thing of this article. If you really want to have a smarter look, use Notepad ++ instead.
When you have a whole workbook locked, do the same thing for the workbook.xml file described above. Thereafter you can enjoy the result because the unwanted password is gone and your document is not protected anymore. In order to make sure, that all the changes have been applied, just go to the “File” -> “Info” again and see what happened (Pic. 12).

Excel file unprotected

Pic. 12 Excel workbook unprotected as seen in the file information.

Because the yellow label is gone, your file is not protected anymore.  The information about the locked workbook structure is also gone, which means that our process has been successful.

The thing looks more complicated when we have no access to the VBA project. Basically, if we don’t particularly need to change the VBA code in our workbook it’s fine. We can follow the process above and should be ok. However, sometimes the VBA code might trigger the automatic protection of some particular sheet. If this is so, even with the best will in the world we won’t be able to unlock the worksheet with the aforementioned method.
In this case, we can use the 7Zip software again. In our /xl/ folder we should find the vbaProject.bin file, just above the workbook.xml one (Pic. 13).

Excel VBA project bin

Pic. 13 The vbaProject.bin file location in the /xl/ directory.

We can access to this file because it works analog to our workbook file – it’s just another directory containing the specified VBA code placed in the specified worksheet. Unfortunately, we can’t open the files physically, even after the extraction. Adding up the .bas extension won’t work too. The only way to read this file is with Notepad ++, which can access inside (Pic. 14).

Exccel VBAproject bin file in Notepad ++

Pic. 14 Our vbaProject.bin file opened in Notepad++ with the most important line of code marked red.

There is been told, that Notepad ++ cannot cope with the .bin file extension and we need a separate tool – HEX Editor. It’s independent software for Windows, but it also can be a plugin for Notepad ++.  It’s not true, at least for newer versions of the Notepad ++ (I guess from 6.0 onwards), because between these terrible blobs, we can find some important lines of code (Pic. 14). It means, that it’s enough to run the .bas file and find the line of code commencing with DPB using, for instance, the Ctrl+F as previously (Pic. 15). Next, we must change the “DPB” to “DPx” (Pic. 15), save the file, and export it back to the 7Zip directory, where it should be replaced.

Reading and finding the code in bin file in Notepad++

Pic. 15 Finding the “DPB” in the .bin file and replacing it with “DPx” by Notepad ++.

When everything is ready, we can launch our Excel workbook again. The first impression is not the best, as we get the following alert (Pic. 16).

Excel changes in VBA code

Pic. 16 Alert informing about the changes done in the VBA project.

We should click “OK” and “Continue Loading Project”. When the project is loaded, go to the VBA console, where you will be welcomed with another alert (Pic. 17). By clicking “OK” you will be able to see at least the list of sheets, that you weren’t able before (Pic. 17).

Excel VBA priject unexpected error

Pic. 17 Unexpected error in our VBA Excel project.

Now you must right-click and select the “VBA project properties”, where you should switch to the “Protection” section (Pic. 18). There is an option of “Lock project for viewing” which initially is selected. You have to untick it if you wish to see your VBA project.

Excel VBA project protection section

Pic. 18 Unlocking the VBA Excel project for viewing.

The last step here is to run the workbook again in order to make the error disappear. Finally, you have full access to the VBA project in your Excel workbook again (Pic. 19).

VBA Excel unprotected

Pic. 19 The unprotected VBA Excel project.

Now you can set the new password or keep it unprotected. As you could notice, the whole process is not difficult, but you must spend a while.

Mariusz Krukar

Links:

  1. Notepad ++ Hex edit
  2. remove_vba_project_password.bas (up to 32 bit system)
  3. StackOverflow: remove_vba_project_password.bas (64 bit system)
  4. https://www.systoolsgroup.com/how-to/break-vba-password-in-excel/
  5. https://www.makeuseof.com/tag/recover-excel-vba-password/
  6. SHEET and SHEETS Functions in Excel
  7. How To Get The Current Sheet Number Of A Workbook?
  8. Determining a Worksheet’s Number
  9. Excel SHEET Function

Forums:

  1. https://superuser.com/questions/807926/how-to-bypass-the-vba-project-password-from-excel
  2. https://stackoverflow.com/questions/1026483/is-there-a-way-to-crack-the-password-on-an-excel-vba-project
  3. https://stackoverflow.com/questions/272503/removing-the-password-from-a-vba-project
  4. https://stackoverflow.com/questions/60641199/use-notepad-as-hex-editor
  5. extracted VBA hex files from vbaproject.bin – how to extract VBA code?
  6. How do I determine the sheet number in Excel when they’ve been renamed?

Youtube:

locked project is unviewable vba excel word

While in Visual Basic Editor (VBE), you click on a VBA project and receive the ‘Project is unviewable‘ error, instead of a password input prompt. You can neither view, nor edit macros. 

This article presents the 2 main reasons behind this message. We will also show you how you may be able to gain access to the VBA code inside the locked project.

If you have received the file from another person, the most likely scenario is that the workbook or add-in author locked macros to prevent users from viewing or editing his or hers VBA code. 

Software tools, such as our popular Unviewable+ VBA application, can protect macros, by making a VBA project unviewable in VBE. In addition, VBA debug mode is disabled, so macros cannot be traced when an error occurs. 

​​If the author locked the project using the Unviewable+ VbaDiff level (lowest security), you can use the VbaDiff Windows application to review the code, even if macros are not accessible in Excel.

If the project has been locked with a higher level of protection, it means that the author would like to protect his or hers intellectual property from all 3rd parties. Any attempt to view or extract VBA code from Unviewable+ protected projects may be a violation of your software license agreement. Depending on your jurisdiction, you may be liable for civil compensation or subject to criminal charges. 

Testimonial for Project is Unviewable+ VBA for Excel

Workbook Is In Shared Mode

Several Excel features are unavailable in Shared workbooks. Developers cannot write, record, change, view or assign macros, as VBA is unviewable. Users can only run existing macros that don’t access unavailable features. 

Here is what to do in order to view macros:

  • Use our Macro Mover add-in to unlock VBA in a Shared workbook
  • Unshare the workbook from: Review Tab > Unshare Workbook

How to unshare workbook in Excel 2016

unshare workbook in Excel 2016

  • Remove From My Forums
  • Question

  • Hi,

    Calling all Guru’s out there!

    I have a spreedsheet which i have setup full now want to add macros to my workbook and apparently there already a couple macros in there. They are locked when i got VBA Editor everything is locked and asks for a password which I do not know.

    I have tried to use a hex editor and replace the string from «DPB=» TO «DPx=» which does not work because i have searched for this string in the file and it does not exist anywhere.

    Can someone please help me out.

    Cheers

Answers

  • if you don’t want to use the existing macro’s; you could save as: spreadsheet without macro’s and then add your own macro’s. I’m no Guru, so this is the only option i know :)

    • Proposed as answer by

      Monday, May 6, 2013 10:01 AM

    • Marked as answer by
      Damon Zheng
      Monday, July 1, 2013 1:19 PM

  • Open new file and copy using Shift and mouse button to select all sheets.

    Then Right click/copy to new workbook (or selected one).


    Oskar Shon, Office System
    MVP

    Press if Helpful; Answer when a problem solved

    • Proposed as answer by
      Mr. Rik
      Wednesday, May 8, 2013 8:14 PM
    • Marked as answer by
      Damon Zheng
      Monday, July 1, 2013 1:19 PM

Понравилась статья? Поделить с друзьями:
  • Vba excel rgb colors
  • Vba excel private sub что это
  • Vba excel split примеры
  • Vba excel return from function
  • Vba excel spinbutton пример