PDA

View Full Version : Solved: Error Handling Question



mbake16
02-21-2009, 10:35 AM
I've created a macro which prompts the user for the password to unprotect a sheet. I've added error handling code to loop the macro back to the beginning if the user enters an incorrect password in the inputbox. The macro works fine if the user enters an incorrect password once, however if the user enters an incorrect password during the second pass the macro errors. It seems it ignores the error handling code on the second pass. The code is below, any insight would be great!

Sub unprotect()
Dim password As String
Dim MyErr As String
a:
On Error GoTo b:
password = InputBox("Unprotect")
Sheet1.unprotect password:=password
b:
MyErr = Err.Number
If MyErr <> 0 Then
On Error GoTo 0
MsgBox "Incorrect Password", vbOKOnly
GoTo a:
End If
End Sub

edit lucas: VBA tags added to code. You can format your code for the forum if you select your code and hit the vba button when posting.

Paul_Hossler
02-21-2009, 11:25 AM
I'd use 'Resume' to return from the error handling code. That allows you to try the error causing statement again

Also I think you want a 'Exit Sub" to avoid executing the error handling code



Sub unprotect()
Dim password As String
Dim MyErr As Long

password = InputBox("Unprotect")

On Error GoTo b
Sheet1.unprotect password:=password

Exit Sub

b:
MsgBox "Incorrect Password", vbOKOnly
Err.Clear
password = InputBox("Unprotect")
Resume

End Sub



Paul

Kenneth Hobs
02-21-2009, 12:45 PM
If you don't need to tell the user that their password was wrong:
Sub Unprotect()
Dim password As String
a: password = InputBox("Unprotect")
On Error GoTo a
ActiveSheet.Unprotect password:=password
End Sub

mbake16
02-22-2009, 10:31 AM
Thank you! The Resume statement did the trick! I wasn't aware that it worked that way, appreciate the tip!

Matt