简体   繁体   English

使用VBA保护VBA项目

[英]Protect VBA project using VBA

When my VB project finishes running, it saves a new copy of the excel workbook, and then e-mails this to a provided distribution. 当我的VB项目完成运行时,它将保存excel工作簿的新副本,然后通过电子邮件将其发送到提供的分发中。 When the code is run, the VB project should be unprotected, allowing any error thrown by the VBE to be "debugged" (which is not possible for locked projects - unfortunately the reasons for debugging cannot be accounted for within the error handler; it's mainly relating to a query which runs against a SQL server database). 运行代码时,VB项目应不受保护,允许VBE抛出的任何错误都被“调试”(对于锁定的项目是不可能的-不幸的是,错误原因不能在错误处理程序中解释调试的原因;主要是与针对SQL Server数据库运行的查询有关)。

However, I wish for the VB project to be protected once it's saved down as the new copy, preventing anyone who receives the distributed copy being able to access the VB project. 但是,我希望将VB项目保存为新副本后对其进行保护,以防止收到分布式副本的任何人都可以访问VB项目。

I've had a search, and couldn't seem to find any answer relating to locking a VB project using VBA. 我进行了搜索,但似乎找不到与使用VBA锁定VB项目有关的任何答案。 Any guidance is appreciated. 任何指导表示赞赏。

Based on this thread : 基于此线程

Sub ProtectVBProject(WB As Workbook, ByVal Password As String) 

    Dim VBP As VBProject, oWin As VBIDE.Window 
    Dim wbActive As Workbook 
    Dim i As Integer 

    Set VBP = WB.VBProject 
    Set wbActive = ActiveWorkbook 

    ' Close any code windows To ensure we hit the right project 
    For Each oWin In VBP.VBE.Windows 
        If InStr(oWin.Caption, "(") > 0 Then oWin.Close 
    Next oWin 

    WB.Activate 
    ' now use lovely SendKeys To unprotect 
    Application.OnKey "%{F11}" 
    SendKeys "+{TAB}{RIGHT}%V{+}{TAB}" & Password & "{TAB}" & Password & "~" 
    Application.VBE.CommandBars(1).FindControl(Id:=2578, recursive:=True).Execute 
    WB.Save 
End Sub 

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

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