1

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.

3
  • Why not cut the routine up to saving a new copy then protect it manually and email it afterwards. I'm assuming we're only talking about 1 file. Commented Jun 30, 2015 at 9:44
  • It's an option.. if it is possible to automate though, the lazy side in me would rather that. Commented Jun 30, 2015 at 9:59
  • ozgrid.com/forum/showthread.php?t=13006&p=65776#post65776 Commented Jun 30, 2015 at 10:41

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Maciej.. from reading the thread I have noted that it's absolutely not a good idea to use send keys. I have chosen not to go ahead and use this solution, however I will accept your answer as it appears to be the only solution available (although with some risk). Thanks!
Have you looked into using Windows API? stackoverflow.com/questions/30508341/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.