Reputation: 2985
When my VB project finishes running, it saves a new copy of the excel workbook, and then e-mails this to a provided distribution. 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).
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.
I've had a search, and couldn't seem to find any answer relating to locking a VB project using VBA. Any guidance is appreciated.
Upvotes: 1
Views: 1998
Reputation: 8591
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
Upvotes: 2