简体   繁体   中英

Protect VBA Project using Excel Add-in

The requirement is to protect the VBA Project of an workbook with password using Excel-Add-in.

Is this possible?

Currently we have an Excel Add-in (xlam) which does all the operation on each of the workbooks opened. We achieved locking of worksheets via Add-in. Now we also want to protect the VBA of those opened workbooks. Below is the code which we found from various forums

With Application
'execute the controls to lock the project
.VBE.CommandBars("Menu Bar").Controls("Tools") _
    .Controls("VBAProject Properties...").Execute
'activate protection
.SendKeys "^{TAB}"
'CAUTION: this either checks OR UNchecks the
'Lock Project for Viewing checkbox, if it's already
'been locked for viewing, then this will UNlock it\
.SendKeys "{ }"
'enter password
.SendKeys "{TAB}" & VBAProjectPassword
'confirm password
.SendKeys "{TAB}" & VBAProjectPassword
'scroll down to OK key
.SendKeys "{TAB}"
'click OK key
.SendKeys "{ENTER}"
'the project is now locked - this takes effect
'the very next time the book's opened...
End With

But issue with this code is it protects the VBA of Add-in itself rather than workbook. We need some code or workaround to protect the VBA of workbook via code which will be written in Excel add-in.

That SendKeys approach will only ever operate on whichever project is active in the VBE... which may or may not be the add-in project.

The VBIDE API doesn't expose anything to programmatically protect a VBProject, so SendKeys is the only way - however you should close all opened code windows and activate the host workbook in order to ensure you're hitting the correct target project, as described in this ozgrid post .

Note that VBA macro protection is easily defeated , so it's more of an annoyance for the VBA dev that needs to maintain the project(s) than it is for someone that would want to crack it open: it's a rather symbolic protection, more than anything else.. however VBE add-ins that parse and process the code in the VBE, such as Rubberduck (disclaimer: I'm heavily involved with that project) will not parse protected VBA projects, so project protection can be used to boost static code analysis performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM