10
votes

I have recently started writing some Macro's in Excel. I have a protected worksheet, and a few buttons that allow the user to add/remove columns/rows at a certain point in the spreadsheet.

I currently unprotect the worksheet, perform the functions and then protect the worksheet.

The problem is, is that the protected sheet password is in plain text in the macro for any curious eyes to see.

How can I have a password on the sheet to protect it, but at the same time, allow my Macro to unprotect the spreadsheet whilst it performs its functions, and then reprotect it, without typing the plaintext password in the macro?

3

3 Answers

16
votes

Two options:

  1. Password protect the VBA. (While VBA protection is far from secure against malicious intent, it is no worse than the security of sheet protection)
  2. If you set the worksheet protection using VBA you can specify UserInterfaceOnly:=True.

    sh.Protect Password:="Password", UserInterfaceOnly:=True

    Once set in this way VBA code can modify the sheet without supplying a password. Since the password must be supplied once to apply protection in the first place, run this code from a seperate workbook or addin you keep to yourself.

1
votes

You can call a UserForm to handle the password prompt, but mask the characters by using PasswordChar as a textbox property.

enter image description here

0
votes

I found some code a while back which may be of some help. This will unlock any password protected worksheet. It takes a little time depending on the length of the password, but essentially it just sledgehammers its way through, and unlocks the worksheet. May not be the most efficient answer to your question, but its a useful bit of code to have nonetheless.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ActiveSheet.ProtectContents = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub