隔离Excel VBA脚本以运行特定的工作表?

时间:2015-10-07 13:00:19

标签: excel vba excel-vba spreadsheet password-protection

  • 我有一个包含7个工作表的Excel电子表格。
  • 每当保存文档时,我都需要将以下脚本仅应用于部分工作表 Sheet6 & Sheet7 )。

我花了几个小时尝试不同的修改,其中一定不起作用。 VBA调试器不会抛出任何错误,当我测试脚本时,它似乎永远不会运行。

每当我从任何工作表标签中保存文档时,如何修改以下脚本以针对特定工作表运行?

谢谢

VBA - Lock Cells&保存表格保存

下面的脚本将锁定包含值的单元格,然后在保存之前用密码保护工作表。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    On Error Resume Next
    Dim Cell As Range
    With ActiveSheet
        .Unprotect Password:=""
        .Cells.Locked = False
        For Each Cell In Application.ActiveSheet.UsedRange
            If Cell.Value = "" Then
                Cell.Locked = False
            Else
                Cell.Locked = True
            End If
        Next Cell
        .Protect Password:=""
         'Protect with blank password, you can change it
    End With
    Exit Sub
End Sub

Script Source

3 个答案:

答案 0 :(得分:1)

更改ActiveSheet并使用For Each循环,如下所示:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    On Error Resume Next
    Dim Cell As Range
    For Each sh In Array("Sheet1", "AnotherSheet", "OtherSheet")   
        With Sheets(sh)
            .Unprotect Password:=""
            .Cells.Locked = False
                For Each Cell In Application.ActiveSheet.UsedRange
                    If Cell.Value = "" Then
                        Cell.Locked = False
                    Else
                        Cell.Locked = True
                    End If
                Next
            .Protect Password:=""
        End With
    Next
End Sub

答案 1 :(得分:0)

这应该会对您有所帮助(当您遇到此事件以及它何时开始时,您会收到消息让您知道:

WHERE name = ...

答案 2 :(得分:0)

可以显着缩短代码(运行时间)
  • 使用SpecialCells而不是循环遍历每个单元格
  • 避免将空白单元格设置为锁定两次(与第一点相比较小)。

更新

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

For Each sh In Array("Sheet1", "AnotherSheet", "OtherSheet")
        With Sheets(sh)
            .Unprotect
            .Cells.Locked = True
                On Error Resume Next
                .Cells.SpecialCells(xlBlanks).Locked = False
                On Error GoTo 0
            .Protect
        End With
    Next
End Sub