简体   繁体   中英

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
    Do
        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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM