Filled Cells
我假设, Cell有Formulas
or Constants
or 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