Unprotecting VBE Project to Make Code Changes

K

Kaisies

I found this code that uses sendkeys for unlocking/locking your VBE Project :

Sub UnprotectVBProject(WB As Workbook, ByVal Password As String)
Dim vbProj As Object

Set vbProj = WB.VBProject

'can't do it if already unlocked!
If vbProj.Protection <> 1 Then Exit Sub

Set Application.VBE.ActiveVBProject = vbProj

' now use lovely SendKeys to quote the project password
SendKeys Password & "~~"

Application.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute
End Sub

Sub ProtectVBProject(WB As Workbook, ByVal Password As String)
Dim vbProj As Object

Set vbProj = WB.VBProject

'can't do it if already locked!
If vbProj.Protection = 1 Then Exit Sub

Set Application.VBE.ActiveVBProject = vbProj

' now use lovely SendKeys to set the project password


SendKeys "+{TAB}{RIGHT}%V{+}{TAB}" & Password & "{TAB}" & Password & "~"

Application.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute

WB.Save
End Sub


Also modifying Chip's information on removing/adding Subs from Projects, I
created this Sub:

Sub DeleteCodeLine(WB As Workbook, ModuleName, StartLine)
Dim VBCodeMod As CodeModule

Set VBCodeMod = WB.VBProject.VBComponents(ModuleName).CodeModule
With VBCodeMod
.DeleteLines StartLine, 1
End With

End Sub



I then have a commandbutton that Does this then: (where sheetname is the
other workbook I want to unprotect / reprotect


UnprotectVBProject Workbooks(sheetname), "abc"
DeleteCodeLine Workbooks(sheetname), "sheet28", 2
ProtectVBProject Workbooks(sheetname), "abc"


When I click the commandbutton it gives me an error:

Run-time error '50289':

Can't perform operation since the project is protected.


I know I'm doing something stupid wrong, but, I can't figure out what...
anyone care to take a stab at it?

Thanks!

-Kaisies
 
K

Kaisies

The error occurs on the:

Set VBCodeMod = WB.VBProject.VBComponents(ModuleName).CodeModule

line of code in the Sub DeleteCodeLine
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top