# Solved: VBA Excel 03 Unprotect Worksheet



## jsanders95 (Jan 8, 2011)

I am writing code for a spreadsheet in VBA (I am using Excel 2003 on WinXP). I have a command button to protect the worksheet (with a password), and one to unprotect it. The code that I am using for the unprotect button is


```
Sub CommandButton5_click()
ActiveSheet.Unprotect
End Sub
```
This works fine, as long as the correct password is entered. If you enter the wrong password, Excel comes up with and error box with the heading 'Visual Basic' , a white cross in a red circle and the text '400'. How could I make excel instead produce a message box saying 'Wrong Password', and produce the password box again?

Thanks (and sorry if this post is a bit rambling!)

James


----------



## andythepandy (Jul 2, 2006)

You could use on error goto to handle the error:

```
Sub CommandButton5_click()
upt
End Sub


Sub upt()
Dim pword As String
pword = InputBox("Enter password", "Unprotect sheets")

On Error GoTo pworderror
ActiveSheet.unprotect Password:=pword
Exit Sub

pworderror:
    If MsgBox("Incorrect password", vbRetryCancel, "Error") = vbRetry Then
        upt
    End If
End Sub
```
Hope that helps


----------



## jsanders95 (Jan 8, 2011)

Thanks, worked perfectly. Sorry for the delay in response - I couldn't try it until now (I'm 15, and doing work experience, and was doing different tasks until today)


----------



## andythepandy (Jul 2, 2006)

Glad it helped  What's the work experience you're doing?


----------



## jsanders95 (Jan 8, 2011)

I'm working with Halcrow - this was for the modellers (a spreadsheet of macros to create multiple charts from data).


----------



## andythepandy (Jul 2, 2006)

Nice  well good luck with the rest of it


----------

