Program with Passwords and Encryption
You can set passwords and encryption options in code using the Workbook object’s security members, such as the Password property and SetEncryptionProperties method. From a security standpoint, it doesn’t make sense to hardcode passwords into Visual Basic macros. Instead, the Workbook object’s security members are generally used in conjunction with User Forms to set passwords and encryption chosen by the user through a customized interface.
For instance, you might create a document template (.xlt) for secure documents that can only be saved using a password and encryption. Such a template might include a user form to get the password, as shown in Figure 26-6.

Figure 26-6. Password user form
The code for the user form confirms that the Password and Confirm Password text boxes match and allows the user to cancel the operation, as shown here:
' Public fields
Public Password As String, Encrypt As Boolean
Private Sub cmdCancel_Click( )
Me.Hide
Password = ""
End Sub
Private Sub cmdSave_Click( )
If txtPassword.Text <> txtConfirm.Text Then
MsgBox "Password and confirm password must match.", , "Confirm Error"
Else
Password = txtPassword.Text
Encrypt = chkEncrypt.Value
Me.Hide
End If
End SubThen, the Secure template includes a workbook-level procedure to intercept the Save event. Whenever the user saves a document based on this template, the following code ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access