PDA

View Full Version : InputBox OK and Cancel Button Problem



mackypogi
05-25-2014, 07:21 PM
I have this macro code that can protect and unprotect, It will show the input box and ask for a password. my problem is when I choose cancel, it still protect the file, the same thing with my unprotect code. here is my code below

Protect Code

Sub ProtectAll()

Dim wSheet As Worksheet
Dim Pwd As String

Pwd = InputBox("Enter your password to protect all worksheets", "Password Input")
For Each wSheet In Worksheets
wSheet.Protect Password:=Pwd
Next wSheet

End Sub

UnProtect Code

Sub UnProtectAll()

Dim wSheet As Worksheet
Dim Pwd As String

Pwd = InputBox("Enter your password to unprotect all worksheets", "Password Input")
On Error Resume Next
For Each wSheet In Worksheets
wSheet.Unprotect Password:=Pwd
Next wSheet
If Err <> 0 Then
MsgBox "You have entered an incorect password. All worksheets could not " & _
"be unprotected.", vbCritical, "Incorect Password"
End If
On Error GoTo 0

End Sub

GTO
05-25-2014, 08:24 PM
Hi there,

You are not testing to see if the password matches a prescribed password. Maybe like:


Option Explicit

Private Const PASSWRD = "My password"

Sub ProtectAll()
Dim wSheet As Worksheet
Dim Pwd As String

Pwd = InputBox("Enter your password to protect all worksheets", "Password Input")

If Pwd = PASSWRD Then

For Each wSheet In Worksheets
wSheet.Protect Password:=Pwd
Next wSheet

End If

End Sub

Sub UnProtectAll()
Dim wSheet As Worksheet
Dim Pwd As String

Pwd = InputBox("Enter your password to unprotect all worksheets", "Password Input")

If Pwd = PASSWRD Then

On Error Resume Next
For Each wSheet In Worksheets
wSheet.Unprotect Password:=Pwd
Next wSheet

If Err <> 0 Then
MsgBox "You have entered an incorect password. All worksheets could not " & _
"be unprotected.", vbCritical, "Incorect Password"
End If
On Error GoTo 0

End If

End Sub

Jan Karel Pieterse
05-26-2014, 02:25 AM
If cancel is pressed, the pwd variable contains an empty string, so test for that and act accordingly:

If Len(pwd)>0
'Now protect
Else
'Cancelled
End If

Tom Jones
05-26-2014, 06:41 AM
Cross post

InputBox OK and Cancel Button Problem (http://www.excelfox.com/forum/f2/inputbox-ok-and-cancel-button-problem-1824/)

Jan Karel Pieterse
05-26-2014, 08:56 AM
No thanks for wasting my time.