错误1004对象“ _Worksheet”的方法“保护”失败

时间:2019-07-17 10:37:57

标签: excel vba

运行宏后,我试图再次保护我的床单。它带有Run-time error 1004 Method 'Protect' of object '_Worksheet' failed。运行此脚本之前,所有工作表均不受保护。如果他们事先得到保护,失败仍然会发生。

我尝试将ActiveWorkbook更改为ThisWorkbook。完成此操作后,我可以自行运行ProtectAll。运行整个代码会引起问题。

Option Explicit

Private Const yourPassword As String = "MyPassWord"

Sub ButtonClick()

UnprotectAll

MyMainRutineCall

ProtectAll

End Sub
Sub MyMainRutineCall()

Dim wsA As Worksheet
Dim wbA As Workbook
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim lOver As Long
Dim ary
Dim a As Variant
On Error GoTo errHandler


Set wbA = ActiveWorkbook
Set wsA = ActiveSheet

'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
  strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"

strName = "PDF" _
          & " - " & wsA.Range("G61").Value _

'create default name for savng file
strFile = strName & ".pdf"
strPathFile = strPath & strFile

If bFileExists(strPathFile) Then
  lOver = MsgBox("Overwrite existing file?", _
    vbQuestion + vbYesNo, "File Exists")
  If lOver <> vbYes Then
    'user can enter name and
    ' select folder for file
    myFile = Application.GetSaveAsFilename _
      (InitialFileName:=strPathFile, _
          FileFilter:="PDF Files (*.pdf), *.pdf", _
          Title:="Select Folder and FileName to save")
    If myFile <> "False" Then
      strPathFile = myFile
    Else
      GoTo exitHandler
    End If
  End If
End If

'Select sheets to use
ary = Array(Sheet7.Name, Sheet3.Name)

For Each a In ary
    Sheets(a).Move after:=Sheets(Sheets.Count)
Next a

ThisWorkbook.Sheets(ary).Select

'export to PDF in current folder
ActiveSheet.ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=strPathFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False

'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & strPathFile

exitHandler:
    Exit Sub

errHandler:
    MsgBox "Could not create PDF file"
    Resume exitHandler

End Sub

Sub UnprotectAll()
    Dim sh As Worksheet
    For Each sh In ActiveWorkbook.Worksheets
        sh.Unprotect Password:=yourPassword
    Next sh
End Sub

Sub ProtectAll()
    Dim sh As Worksheet
    For Each sh In ActiveWorkbook.Worksheets
        sh.Protect Password:=yourPassword
    Next sh
End Sub

有问题的是sh.Protect Password:=yourPassword

1 个答案:

答案 0 :(得分:0)

实际上问题似乎是

If myFile <> "False" Then

应为

If myFile <> False Then

因为Application.GetSaveAsFilename method返回的文件名是Variant/StringFalse的名字是Variant/Boolean。但不是字符串"False"

所以我的建议是在更多地方使用ThisWorkbook使其更可靠:

Option Explicit

Private Const yourPassword As String = "MyPassWord"

Sub ButtonClick()

    UnprotectAll

    MyMainRutineCall

    ProtectAll

End Sub

Sub MyMainRutineCall()
    On Error GoTo errHandler

    Dim wbA As Workbook
    Set wbA = ThisWorkbook

    Dim wsA As Worksheet
    Set wsA = wbA.ActiveSheet

    'get active workbook folder, if saved
    Dim strPath As String
    strPath = IIf(wbA.path = vbNullString, Application.DefaultFilePath, wbA.path) & Application.PathSeparator

    Dim strName As String
    strName = "PDF" & " - " & wsA.Range("G61").Value

    'create default name for savng file
    Dim strFile As String
    strFile = strName & ".pdf"

    Dim strPathFile As String
    strPathFile = strPath & strFile

    If bFileExists(strPathFile) Then
        If MsgBox("Overwrite existing file?", vbQuestion + vbYesNo, "File Exists") <> vbYes Then
            ' user can enter name and
            ' select folder for file
            Dim myFile As Variant
            myFile = Application.GetSaveAsFilename( _
                InitialFileName:=strPathFile, _
                FileFilter:="PDF Files (*.pdf), *.pdf", _
                Title:="Select Folder and FileName to save")
            If myFile <> False Then
                strPathFile = myFile
            Else
                GoTo exitHandler
            End If
        End If
    End If

    'Select sheets to use
    Dim ary() As Variant
    ary = Array(Sheet7.Name, Sheet3.Name)

    Dim a As Variant
    For Each a In ary
        ThisWorkbook.Sheets(a).Move After:=ThisWorkbook.Sheets(Sheets.Count)
    Next a

    ThisWorkbook.Sheets(ary).Select

    'export to PDF in current folder
    ThisWorkbook.ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=strPathFile, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False

    'confirmation message with file info
    MsgBox "PDF file has been created: " & vbCrLf & strPathFile

exitHandler:
    Exit Sub

errHandler:
    MsgBox "Could not create PDF file"
    Resume exitHandler
End Sub


Sub UnprotectAll()
    Dim sh As Worksheet
    For Each sh In ThisWorkbook.Worksheets
        sh.Unprotect Password:=yourPassword
    Next sh
End Sub


Sub ProtectAll()
    Dim sh As Worksheet
    For Each sh In ThisWorkbook.Worksheets
        sh.Protect Password:=yourPassword
    Next sh
End Sub