Search code examples
excelvbapasswordsunlock

How to check if the unprotect password of an excel file is correct with vba?


I'm trying to lock an unlock an excel file with VBA. I lock the file in the code with a default password and I give this password to the user in other file. Always is the same password so there's no need to enter it by the user, I'm giving him the file locked at the beginning.

My problem is that I want the user to enter a password in a form to unlock the file and I don't know how check if the password entered by the user is correct before calling the function Unprotect.

I have a sub like this:

Sub Unlock (Pass as String)

    for i=1 to Sheets.Count
        Sheets(i).Unprotect Password:=Pass
    next i

end Sub

If I code this and the password is correct, everything's ok, but if the user makes a mistake, VBA gives an error message out of control of the user. I want to check in the code the password before calling unprotect and if it's wrong, show a msgbox and let user enter a new password again but I don't know if exists any function that check if the password is correct.

I think in a function like this:

Sub Unlock (Pass as String)

    'if password is good
        for i=1 to Sheets.Count
            Sheets(i).Unprotect Password:=Pass
        next i
    'else
        msgbox "Try again!"
    'end if

end Sub

but I don't have any way to know "if password is good".

Thanks for helping and sorry for my English!


Solution

  • One way is to chuck in whatever password you're given, and handle the exception appropriately according to your needs. Here is a decent link:

    http://www.cpearson.com/excel/errorhandling.htm