保护工作表时出现运行时错误'1004'

时间:2018-06-21 12:53:07

标签: excel vba excel-vba

运行由控制盒触发的系统。该代码使用以下代码取消保护程序中几乎所有表的保护(没有问题):

Sub UnprotectSheets()

    Dim wks As Worksheet

    For Each wks In Worksheets
        If wks.Name Like "Source Data Table" Or wks.Name Like "Permit Route Dashboard" _
        Or wks.Name Like "Administrative Tasks" Or wks.Name Like "RP Calculation" Then GoTo Nextwks
        wks.Unprotect Password:="Password"
Nextwks:
    Next

End Sub

然后程序进行分析。最后,我想使用以下代码保护相同的工作表

Sub ProtectSheets()

    Dim wks As Worksheet

    For Each wks In Worksheets
        If wks.Name Like "Source Data Table" Or wks.Name Like "Permit Route Dashboard" _
        Or wks.Name Like "Administrative Tasks" Or wks.Name Like "RP Calculation" Then GoTo Nextwks
        wks.Protect Password:="Password"
Nextwks:
    Next

End Sub

但是-我每次都会收到以下错误消息:

  

运行时错误'1004'对象_Worksheet的'保护'方法失败

感谢您的帮助。谢谢

1 个答案:

答案 0 :(得分:1)

问题是您试图保护已经受保护的工作表。因此,只需运行以下命令即可:

Option Explicit

Sub TestMe()

    Dim wks As Worksheet

    For Each wks In Worksheets
        If wks.ProtectContents Then
            Debug.Print wks.Name & " is protected!"
        Else
            Debug.Print wks.Name & " is not protected!"
        End If
    Next wks

End Sub

然后转到立即窗口( Ctrl + G ),然后查看在此处编写的报告。它应该看起来像这样:

Sheet1 is not protected!
Sheet2 is protected!

通常,除非是为了捕获错误,否则请尽量避免在VBA(和每种编程语言)中使用GoTo。人们一看到这些就会生气。