Password Protection Problem

joeeoj

New Member
Joined
Jun 17, 2010
Messages
19
Hi, recently I needed a way to unprotect all worksheets at once. I was given the idea to create a userform with the following code:

Code:
Private Sub CommandButton1_Click()
    'unprotect worksheets
 
    For Each Worksheet In Worksheets
 
    If Worksheet.ProtectContents = True Then
    Worksheet.Unprotect Password:=TextBox1.Text
    End If
 
    Next Worksheet
 
    MsgBox "Workbook will be re-protected upon exit."
 
    Unload Me
End Sub

This works great, but if the password entered is wrong, a Run-time error '1004' occurs. Is there any way that a message saying "Incorrect Password" comes up instead of this error?

Thanks!
 

Excel Facts

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.

doofusboy

Well-known Member
Joined
Oct 14, 2003
Messages
1,325
You could try something like this:

Code:
Private Sub CommandButton1_Click()
    'unprotect worksheets
 
    [B][COLOR=red]On Error GoTo ErrHandler[/COLOR][/B]
    For Each Worksheet In Worksheets
 
    If Worksheet.ProtectContents = True Then
    Worksheet.Unprotect Password:=TextBox1.Text
    End If
 
    Next Worksheet
 
    MsgBox "Workbook will be re-protected upon exit."
 
    Unload Me
[COLOR=red][B]ErrHandler:
    If Err.Number = 1004 Then
        MsgBox "Incorrect Password"
    End If[/B][/COLOR]
End Sub
 

Forum statistics

Threads
1,136,864
Messages
5,678,210
Members
419,751
Latest member
richkings

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top