VBA Excel ActiveWorkbook.取消保护不删除已知密码



由于某种原因,.Unprotect没有删除密码。我可以使用我制作的宏设置密码,但是当我出于某种原因尝试使用以下代码删除相同的确切密码时ActiveWorkbook.Unprotect Password:=pw_check不起作用。 ActiveWorkbook.HasPassword似乎在应该返回False时返回True。在我的一生中,我找不到任何解释这种行为的帖子,所以我必须得出结论,我用错了.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

看起来ActiveWorkbook.HasPassword反映了您在SaveAs方法中使用相关参数(或通过 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

最新更新