由于某些原因,.Unprotect
没有删除密码。
我可以使用我创建的宏来设置密码,但是由于某种原因ActiveWorkbook.Unprotect Password:=pw_check
不能使用下面的代码删除相同的确切密码时,我可以使用该宏。 ActiveWorkbook.HasPassword
应该返回True
时似乎正在返回False
。为了我的一生,我找不到任何可以解释这种行为的帖子,所以我必须得出结论,我使用了.Unprotect
错误。
Sub RemovePassword()
Dim pw_check As Variant
Dim fname As String
Dim fd As Office.FileDialog
fname = ActiveWorkbook.Name
' Verify with user before continuing '
If MsgBox("You are about to remove password encryption from this file and save. Would you like to continue?", vbYesNo) = vbNo Then Exit Sub
pw_check = "KNOWN_PASSWORD"
retry_pass:
ActiveWorkbook.Unprotect Password:=pw_check
Debug.Print (ActiveWorkbook.HasPassword)
If ActiveWorkbook.HasPassword = False Then
' prep file dialog window '
Set fd = Application.FileDialog(msoFileDialogFilePicker)
' With file dialog set title, clear filters if any, and validate if show was valid and can save or not. '
With fd
.Title = "Please select where to save the encrypted file."
.Filters.Clear
If .Show = True Then
On Error GoTo exit_sub
ActiveWorkbook.SaveAs fileName:=ActiveWorkbook.Name
MsgBox "File: " & fname & " saved!"
Else
MsgBox "Cancelled"
End If
End With
Else
pw_check = Application.InputBox("Invalid password please provide another password and try again.")
If pw_check = False Then
MsgBox ("Process cancelled.")
GoTo exit_sub
ElseIf pw_check = vbNullString Then
MsgBox ("Nothing was entered.")
GoTo retry_pass
Else
GoTo retry_pass
End If
End If
exit_sub:
End Sub
答案 0 :(得分:1)
类似ActiveWorkbook.HasPassword
反映的是您在SaveAs
方法中使用相关参数(或通过“另存为”对话框手动使用)时所应用的密码,而不是使用Protect
方法所应用的密码。
Sub Tester()
Debug.Print "1", ThisWorkbook.HasPassword '>> False
ThisWorkbook.Protect "blah"
ThisWorkbook.Save
Debug.Print "2", ThisWorkbook.HasPassword '>> False
ThisWorkbook.Unprotect "blah"
Debug.Print "3", ThisWorkbook.HasPassword '>> False
ThisWorkbook.SaveAs ThisWorkbook.FullName, Password:="blah"
Debug.Print "4", ThisWorkbook.HasPassword '>> *True*
ThisWorkbook.SaveAs ThisWorkbook.FullName, Password:=""
Debug.Print "5", ThisWorkbook.HasPassword '>> False
End Sub