简体   繁体   English

使用Excel加载项保护VBA项目

[英]Protect VBA Project using Excel Add-in

The requirement is to protect the VBA Project of an workbook with password using Excel-Add-in. 要求是使用Excel-Add-in保护工作簿的VBA项目的密码。

Is this possible? 这可能吗?

Currently we have an Excel Add-in (xlam) which does all the operation on each of the workbooks opened. 目前我们有一个Excel加载项(xlam),它可以对打开的每个工作簿执行所有操作。 We achieved locking of worksheets via Add-in. 我们通过加载项实现了工作表的锁定。 Now we also want to protect the VBA of those opened workbooks. 现在我们还想保护那些打开的工作簿的VBA。 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. 但是这个代码的问题是它保护了加载项本身的VBA而不是工作簿。 We need some code or workaround to protect the VBA of workbook via code which will be written in Excel add-in. 我们需要一些代码或解决方法来通过将在Excel加载项中编写的代码来保护工作簿的VBA。

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. SendKeys方法只能在VBE中活动的任何项目上运行...这可能是也可能不是加载项目。

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 . VBIDE API没有公开任何东西以编程方式保护VBProject,所以SendKeys 唯一的方法 - 但是你应该关闭所有打开的代码窗口并激活主机工作簿,以确保你达到正确的目标项目,如这个ozgrid的帖子

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. 请注意,VBA宏保护很容易被破坏,因此对于需要维护项目的VBA dev来说,这比想要破解它的人更烦恼:它是一个相当具有象征意义的保护,比什么都重要否则..但解析和处理VBE中的代码的VBE加载项,如Rubberduck (免责声明:我大量参与该项目)将无法解析受保护的VBA项目,因此可以使用项目保护来增强静态代码分析表现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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