Excel:locking和保护整个excel报告中只填充的单元格
有没有办法lockingexcel报告中所有表格中的所有填充单元格? 我会很高兴,如果有这个excel属性。如果不是vba代码是好的。 我find了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
请为此提出一个更好的方法。
提前致谢。
通过Filled Cells
我假设,单元格有Formulas
或Constants
或Comments
。
看到你可以在你的代码中join这个例子。 这不会遍历每个单元格,而是使用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
FOLLOWUP(来自评论)
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