MrExcel Publishing
Your One Stop for Excel Tips & Solutions

Deleting Modules & Macros with Code

Posted by Chris on September 06, 2001 6:52 AM

I have some code that deletes all code within a project. However, the project I try to delete with this code is protected with a password. I know the password so that is not a problem but what is the line of code I need to insert in my module to unprotect the project so that I do not need to manually unprotect it and then run the sub routine?


Posted by Damon Ostrander on September 06, 2001 10:45 AM


I just did a quick check of the VBproject object model and don't find anything that indicates it is possible to protect or unprotect a VBproject from within VBA. VBA can only test (read-only) whether a VBproject is protected or not. If would have very interesting implications if a VBproject's protection could be changed from VBA, because it would mean that a VBproject could set or remove its own protection.

One thing you might therefore try as a last resort is to remove and reset the protection using SendKeys to actually send the necessary keystrokes to the VBE user interface.


Posted by Ivan F Moala on September 06, 2001 9:34 PM

Trry something like this;

Option Explicit

Const BreakIt As String = "%{F11}%TE+{TAB}{RIGHT}%V{+}{TAB}"

Sub Change_VBA_PW()
Dim WB As Workbook
Dim Password As String

Set WB = ActiveWorkbook
Password = "test"
Call SetVBProjectPassword(WB, Password)

End Sub

Sub SetVBProjectPassword(WB As Workbook, ByVal Password As String)
'Needs reference to Visual Basic for Applications Extensibility Library
Dim VBP As VBProject
Dim OpenWin As VBIDE.Window
Dim i As Integer

Set VBP = WB.VBProject

Application.ScreenUpdating = False

' close any code windows to ensure we are in the right project
For Each OpenWin In VBP.VBE.Windows
If InStr(OpenWin.Caption, "(") > 0 Then OpenWin.Close
Next OpenWin


'Application.OnKey "%{F11}"
SendKeys BreakIt & Password & "{tab}" & Password & "~" & "%{F11}~", True
'SendKeys "enter", True
Application.ScreenUpdating = True
SendKeys "%{F11}", True
End Sub