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 Sub
Then, 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 ...
Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.