I personally would avoid sendkeys if at all possible, which in this case I believe sendmessage would be better. Of course that wasn't your question, and I don't have the api code handy, so...

For sendkeys to work, the window has to be visible and have the focus.

Hence - you need to make the vbe window visible before sending keys to the menubar.



[VBA]Option Explicit
Sub LockVBAProject()



With Application


.VBE.MainWindow.Visible = True



'//execute the controls to lock the project\\

'the first line below ".vbe.commandbars......" is the line in which i get the error.
'error msg Run-time error '1004', app-defined or obj-def error

'******************************************************
.VBE.CommandBars("Menu Bar").Controls("Tools").Controls("VBAProject Properties...").Execute
'******************************************************

'//activate 'protection'\\
.SendKeys "^{TAB}"
'//CAUTION: this either checks OR UNchecks the\\
'//"Lock Project for Viewing" checkbox, if it's already\\
'//been locked for viewing, then this will UNlock it\\
.SendKeys "{ }"
'//enter password (password is 123 in this example)\\
.SendKeys "{TAB}" & "123"
'//confirm password\\
.SendKeys "{TAB}" & "123"
'//scroll down to OK key\\
.SendKeys "{TAB}"
'//click OK key\\
.SendKeys "{ENTER}"

'the project is now locked - this takes effect

.VBE.MainWindow.Visible = False
End With

End Sub
[/VBA]