VBA: How can I password protect modules using code?

I have an file which saves a copy of itself to go to certain recipients, so you end up with many files that only contain recipient-specific information and the original maste file that contains all information. When the recipient-specific files are made, I have code that deletes everything but information that is related to that recipient and locks down the workbook and sheets with a randomly made password using the below function:

Function Pwd(iLength As Integer) As String
Dim i As Integer, iTemp As Integer, bOK As Boolean, strTemp As String
'48-57 = 0 To 9, 65-90 = A To Z, 97-122 = a To z
'amend For other characters If required
For i = 1 To iLength
        iTemp = Int((122 - 48 + 1) * Rnd + 48)
        Select Case iTemp
        Case 48 To 57, 65 To 90, 97 To 122: bOK = True
        Case Else: bOK = False
        End Select
    Loop Until bOK = True
    bOK = False
    strTemp = strTemp & Chr(iTemp)
Next i
Pwd = strTemp
End Function

Is it possible to also lock down the modules so that they cannot be edited? What I want is the same functionality that Excel provide in Visual Basic by going to Tools -> VBAProject - Project Properties -> Protection, but to do this through the code so that it can be applied to each of the recipient specific files.

I can apply protection to the sheets using code like:

Sheets(1).Protect Password, True, True

And to the workbook with code like:

ActiveWorkbook.Protect Password, True, False

But is there something that I can use to lock down the modules?


Notwithstanding the good advice already given about the security of Excel passwords/protection, and the comprehensive (non-SendKeys) solution linked by Carl Colijn, I have used the dirty SendKeys method myself with some success - see example below, and here for more details on SendKeys. YMMV etc.

Note you will have to find the option "Trust access to the VBA project object model" in the Excel Trust Center > Macro Settings, or equivalent for your version of Excel

Sub UnprotectVBProj(ByRef WB As Workbook, ByVal Pwd As String)

    Dim vbProj As Object

    Set vbProj = WB.VBProject

    If vbProj.Protection <> 1 Then Exit Sub ' already unprotected

    Set Application.VBE.ActiveVBProject = vbProj

    SendKeys "%TE" & Pwd & "~~"

End Sub

Sub ProtectVBProj(ByRef WB As Workbook, ByVal Pwd As String)

    Dim vbProj As Object

    Set vbProj = WB.VBProject

    If vbProj.Protection = 1 Then Exit Sub ' already protected

    Set Application.VBE.ActiveVBProject = vbProj

    SendKeys "%TE+{TAB}{RIGHT}%V%P" & Pwd & "%C" & Pwd & "{TAB}{ENTER}"

End Sub

Need Your Help

svn: /etc/subversion/servers:6: Section header expected

svn unix proxy

I have to add proxy in the /etc/subversion/servers file.

Newrelic exceptions still being logged


Newrelic is logging exceptions generated by our application even though we have specified in the yaml file not to log particualr exceptions