有没有办法在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
请为此建议一个更好的方法。
提前致谢。
答案 0 :(得分:0)
我假设Filled Cells
,小组有Formulas
或Constants
或Comments
。
请参阅此示例,您可以将其合并到代码中。这不会遍历每个单元格,而是使用SpecialCells
<强> UNTESTED 强>
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