Project is unviewable как снять защиту vba word
When I try to edit or step into my VBA code for debugging purpose I get "Project is Unviewable". I have created .dotm file at location (C:\Users\UserName\AppData\Roaming\Microsoft\Word\STARTUP).
8 Answers 8
When launched automatically at startup the VBA project in .DOTM files are not viewable. I couldn't find this clearly documented by Microsoft but I tested/replicated it across multiple OS and versions of Office to conclude it was "by design"
There is some ways around it:
Copy template OUT of Start Up Folder, right click file and select "Open" You can debug it.
Ensure you have write permission to file in startup folder. Even if you are Admin, if UAC is ON you won't have access - grant your user "full control" or "write access to file" to DOTM file in startup folder.
Close all instances of Word, right click .DOTM file and Open, you can now debug it.
However you can't save changes - to save changes you must grant permissions for the user to write to the STARTUP folder.
this is not a bug. This is a feature of Microsoft Templates when you open a template it never opens original file rather opens a copy of the template. to modify or debug a template right click on template itself and say open or open word and use Open file dialog to modify the code of the template.
Apologies for reviving an old thread, but is there any way to view the VBA project from a document based on the add-in, without having to open the add-in itself? I have a .dot template that I have made a Global add-in by storing it in the Startup folder. This template has a DocumentOnClose handler that I need to debug. Modifying the template and closing Word doesn't fire this event (at least not for me) so I need to debug the code in the document, not the template. Thoughts anyone?? I can almost get it to work if the template is open in Word at the same time, but this is very tedious.
One trick i can suggest. you can open a new document and insert new module then add one procedure and create a document object now that object you need to set to open your addin file so pass the path of the file and hit F8 key to start debugging you will be able to see the code of the adding written in automatically.
When editing macro-enabled Word documents (for example, .docm files) that are stored on OneDrive, you may receive the following warning:
SECURITY WARNING
Macros have been disabled.
Enabled Content
After clicking Enabled Content , and opening the VBA editor, attempting to view the project may result in the error:
Project is unviewable
After closing and reopening the document, again open the VBA editor. Within the Word document, you will then receive the following message:
EDITING MACROS
Check out this document to view and edit its macros.
Check Out
After checking out out the document, macros may be edited.
Open the .dotm from . /STARTUP location and do modifications and saves there.
Open your DOTM file and on Developer Tab (you will need to enable Dev Tab first 1) and choose Document Template and uncheck items that are currently loaded in under Global templates and add-ins.
However, if I right-click on the .dot file from Windows File Explorer, select Open With, and choose Microsoft Office Word from File Explorer's menu, MS Word opens the file for editing rather than creating a new Document (the name in Word's Title Bar is that of the .dot file I opened). From this instance of Word I can view and edit the macros contained in the .dot file.
Всем привет! Я обычный пользователь MS Excel. Не являющийся профессиональным программистом, но накопивший достаточно опыта, для установки и обхода защиты проектов VBA.
Дисклеймер:
В данной статье рассмотрены виды защиты проектов VBA, от несанкционированного доступа. Их сильные и слабые стороны – ранжирование.
Цель статьи показать слабые и сильные стороны каждого вида защиты проекта VBA в MS Office.
Демонстрация разработанных инструментов, в надстройке Macro Tools VBA, для снятия и установки той или иной защиты.
Все инструменты реализованы стандартными средствами VBA, без использования дополнительных библиотек.
Первый вид защиты — Обычный пароль
Время на снятие: мгновенно
Недостаток: быстрый доступ к запароленному модулю VBA
Стандартный инструмент (В среде VBE: панель Tools -> VBAProject Properties -> Protection).
Самая легко снимающаяся защита. В интернете легко находится код, для снятия данной защиты.
Данную защиту можно снять следующим инструментом:
Второй вид защиты — Project is Unviewable
Время на снятие: от 10 до 15 мин (в ручную)
Недостаток: доступ к исходному коду модуля VBA
Большинство пользователей Excel, не могут снять данную защиту, так как она имеет множество вариации и нюансов, для ее снятие нужно иметь представление о внутренней структуре файла Excel.
Основан, данный вид защиты, на изменение ключей:
в файле vbaProject.bin .
Кратко, как создается данная защита
Для создания данной защиты нужно, разархивировать файл Excel. Перейти в архиве в папку xl, открыть файл vbaProject.bin, в конце файла находятся наши ключи, редактируем значения ключей на пусто, сохраняем файл. Переводим наш архив, обратно в файл Excel. Готово!
Это самый простой вариант данной защиты, но существует множество модификаций.
Алгоритм снятия защиты Project is Unviewable.
1) Разархивируем подопытный файл, переходим в файл …\xl\_rels\workbook.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, запрет сохранения и прочее.
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\_rels\workbook.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. Так и снимаются без особых проблем.
(Oddly when I use the "Attach. " button above (and the .dotm is NOT "currently loaded", I can attach it to a new word document, it opens, no problem with file corruption, no password, no signature, etc). However I want the project loaded EVERY TIME Word starts, without further security adieu.
The .dotm file is in a trusted location. (have also tried other "trusted locations", no luck. )
Macro Settings are "wide open". Have also used C:\Program Files\Microsoft Office 15\root\office15\SelfCert.exe to create signature, apply to .dotm file, no change. Then remove that, again no luck. Tried the .dotm in the trusted location: c:\Users\rick\Documents\portfolios\, no change.
(Above dialogue is unclear vs. "the trust center". Don't you want to have trusted files, trusted locations? Ask every time, do you want to trust this file? do you want to trust this location? Once marked trusted, its trusted so you don't get asked again every time?
Note how the "add-ins" list included the the file I need trusted.
Also note , the definition of "add-ins", vs. "templates" is very confusing.!"Templates" should be standard Word "layouts" , Word "forms" etc. An "add-in" should be a VBA project. A "COM add-in" should be COM based. Confusion above continues. "Active Application Add-ins".
Above implies that the File Location associated with" User Templates" (C:\Users\rick\AppData\Roaming\Microsoft\Templates) is "trusted" . however its not.
Above dialogue is also very strange. Again confusion between "Document Template" vs. "Global Templates and add-ins". In the above you can see my .dotm is Currently Loaded. However it will not open in the VBE. Gets the above "Project Locked" "Project is unviewable".
"Project Locked" "Project is unviewable" error message HELP link is not helpful, top level generic at best!
One thing for certain the "workflow" and "UI" around VBA security is horrible all around!
On the Developer do you really want "Templates". a "Document Panel".
Or should you go to "Add-Ins".
And if we can conclude the UI is poor, the documentation is actually worse.
Becoming a "trusted published" seems a bit like overkill however that may be an option.
Using "Normal" to store a large amount of VBA code is ill advised. When that file get mangled you loose your VBA code in a jiffy. And sadly it does happen.
Hope this entire area gets cleaned up. In the meantime how exactly do you get MSFT to trust your VBA project?
This thread is locked. You can follow the question or vote as helpful, but you cannot reply to this thread.
Удалить пароли с проектов VBA – удаление паролей с проектов VBA, в том числе "Project is UNVIEWABLE", и обратная установка UNVIEWABLE
- «Установить пароль Unviewable» — устанавливает пароль на проект VBA выбранной книги
- «Снять пароль Unviewable» — снимает пароль с проекта VBA выбранной книги
- «Снять пароль VBA» — удаляет пароли со всех активных книг, кроме защищенных паролем «Project is UNVIEWABLE»
Главная панель удаления пароля проекта VBA Unviewable
«Установить пароль Unviewable» — устанавливает пароль на проект VBA выбранной книги Excel и Word
При использовании инструмента открывается диалоговое окно выбора файла для установки пароля — «Project unviewable»
VBAProject is unviewable
Главная панель удаления пароля проекта VBA Unviewable
«Снять пароль Unviewable» — снимает пароль с проекта VBA выбранной книги Excel и Word
При использовании инструмента открывается диалоговое окно выбора файла для снятия пароля — «Project unviewable»
Снятие пароля с проекта VBA "Project unviewable"
Главная панель удаления пароля проекта VBA Unviewable
«Снять пароль VBA» — удаляет пароли с проектов VBA, активных книг Excel
Снятие паролей с проектов VBA Пароли не снимаются с проектов, защищенных ошибкой - "Project unviewable"
You can protect your macro (VBA code) in your MS Office documents from being view-able in the VBA Editor. Most people are aware of the option to password protect your code but this can be bypassed as shown in this blog. There is also a password-less protection option that simply tells the user that the Project is locked and “unviewable” as shown in the image below.
The unviewable option is not able to be set through the MS office application itself, but instead, it needs to be done as a modification to the file after it is saved. This feature is documented as the ProjectProtectionState and ProjectVisibilityState attributes of the PROJECT stream in Office files here.
The ProjectProtectionState and ProjectVisibilityState attributes are encrypted data structures but it turns out that if you set them to something arbitrary, it will protect the document and make it locked/unviewable. If you change only the ProjectVisibilityState it will still show the project structure but not allow viewing of individual code modules. If you change both, you will get the locked/unviewable message immediately upon trying to expand the root of the project and will not be able to see the project structure.
There is a walk through here of how to change your office document to be locked/unviewable, but I would like to provide an automated solution. One major advantage of the automated solution is that it can not only set this protection, it can also remove this protection from any document. I added this feature to Stan Hegt’s (@StanHacked) EvilClippy tool and it can be used as follows.
To set the Locked/Unviewable attributes use the ‘-u’ option:
EvilClippy.exe -u macrofile.doc
To remove the Locked/Unviewable attributes use the ‘-uu’ option:
EvilClippy.exe -uu macrofile.doc
You can remove the Locked/Unviewable attributes on files that were not locked with EvilClippy as well.
Up until this research, the change to make a VBA Project locked/unviewable was said to be irreversible but I discovered that if you simulate a password protected document by setting the ProjectCLSID to all zero’s and use valid values for ProjectProtectionState (CMG), ProjectVisibilityState (GC) and ProjectPassword (DPB) you can undo this protection.
CMG=CAC866BE34C234C230C630C6
DPB=94963888C84FE54FE5B01B50E59251526FE67A1CC76C84ED0DAD653FD058F324BFD9D38DED37
GC=5E5CF2C27646414741474
Above are values that will undo the protection, but because the MS Office Compound File Binary Format (CFBF) is sensitive to data length changes, your best bet is to let EvilClippy make these changes for you.
Bonus: The EvilCippy ‘-uu’ option also removes any password protection from the VBA Project.
Читайте также: