1

有没有办法锁定excel报告中所有工作表中的所有填充单元格(仅)?如果有这方面的 excel 属性,我会很高兴。如果没有 vba 代码就可以了。我找到了 vba 代码,但我们必须提供工作表名称。就像那样,我有很多床单,我无法给出所有床单的名称。

VBA代码:

  Private Sub Workbook_AfterSave(ByVal Success As Boolean)
For Each cl In Sheets("Sheet1").Cells
    If cl = blank Then
        cl.Locked = False
        Else
        cl.Locked = True
    End If
Next
Sheets("Sheet1").Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
Sheets("Sheet1").EnableSelection = xlUnlockedCells
End Sub

请为此提出一个更好的方法。

提前致谢。

4

1 回答 1

0

Filled Cells我假设, Cell有Formulasor Constantsor Comments

请参阅此示例,您可以将其合并到您的代码中。这不会遍历每个单元格,而是利用SpecialCells

未经测试

Sub Sample()
    Dim Rng As Range
    Dim ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        .Cells.Locked = False

        On Error Resume Next

        Set Rng = .Cells.SpecialCells(xlCellTypeConstants)
        Rng.Locked = True

        Set Rng = .Cells.SpecialCells(xlCellTypeFormulas)
        Rng.Locked = True

        Set Rng = .Cells.SpecialCells(xlCellTypeComments)
        Rng.Locked = True

        On Error GoTo 0
    End With
End Sub

如果要将其应用于所有工作表,则只需遍历所有工作表

例如

Sub Sample()
    Dim Rng As Range
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        With ws
            .Cells.Locked = False

            On Error Resume Next

            Set Rng = .Cells.SpecialCells(xlCellTypeConstants)
            Rng.Locked = True

            Set Rng = .Cells.SpecialCells(xlCellTypeFormulas)
            Rng.Locked = True

            Set Rng = .Cells.SpecialCells(xlCellTypeComments)
            Rng.Locked = True

            On Error GoTo 0
        End With
    Next
End Sub

跟进(来自评论)

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim Rng As Range
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        With ws

            .UnProtect

            .Cells.Locked = False

            On Error Resume Next

            Set Rng = .Cells.SpecialCells(xlCellTypeConstants)
            Rng.Locked = True

            Set Rng = .Cells.SpecialCells(xlCellTypeFormulas)
            Rng.Locked = True

            Set Rng = .Cells.SpecialCells(xlCellTypeComments)
            Rng.Locked = True

            On Error GoTo 0

           .Protect
           .EnableSelection = xlUnlockedCells
        End With
    Next
End Sub
于 2013-02-20T07:19:06.917 回答