Down below is my function, for some reason it does not work. If I place a breakpoint in the last if statement and removes sending "%{F11}" it does work. So my guess is that "%F11" is not working. Does anyone have an idea?
Sub UnprotecPassword(wb As Workbook, ByVal projectPassword As String)
Dim currentActiveWb As Workbook
If wb.VBProject.Protection <> vbext_pp_locked Then
Exit Sub
End If
Set currentActiveWb = ActiveWorkbook
wb.Activate
SendKeys "%{F11}"
SendKeys "^r" ' Set focus to Explorer
SendKeys "{TAB}" ' Tab to locked project
SendKeys "~" ' Enter
SendKeys projectPassword
SendKeys "~" ' Enter
If (wb.VBProject.Protection = vbext_pp_locked) Then
MsgBox ("failed to unlock")
End If
currentActiveWb.Activate
End Sub
To test this, Let's create a new workbook called
Book2.xlsm
.for testing purpose paste this code in the Book2 Module.
Protect it with a password say
a
and then close it. This is necessary for the Locking to take effect.Now create a new workbook say Book1 and in the module paste this code.
Now open the 1st workbook that we created; Book2.xlsm. Check the VBA Editor for Book2 and you will notice that it is password protected. You will also notice that it is the active workbook. Activate
Book1
by clicking theView Tab | Switch Workbooks | Book1
Now click on
Developer tab | Macros
If you can't see Developer tab then I would recommend going through this link.Click on the the
Sample
Macro in theMacro Dialog Box
and you are done.If you check the VBA Editor, you will notice that the VBA Editor for Book2 is now unlocked/accessible.
Sendkeys are unreliable depending on your use of it. If you use it correctly then that are pretty much reliable :)
There is one more way to unlock the VBA Password but that is pretty complex and involves invoking the API like FindWindow etc...
Check out these posts for code samples:
http://www.mrexcel.com/archive/VBA/29825.html
http://www.vbaexpress.com/forum/showthread.php?t=30687
And these posts are for info:
http://www.excelforum.com/excel-programming/490883-why-doesnt-sendkeys-work-consistently.html
http://www.ozgrid.com/forum/showthread.php?t=13006
They discuss why using Sendkeys is not very reliable in a multitasking environment and many discourage the use for commercial purpose. However, for unprotecting VBA projects, it appears to be the only solution.
Hope it helps!