【要求】保护工作表C1:C4中的公式,防止被修改。
一、纯手工操作
1、选择整个工作表--自定义单元格格式--保护--取消勾选锁定
2、选中有公式的单元格--自定义单元格格式--勾选锁定和隐藏
3、审阅--保护工作表(设置密码)
可以对上图操作框中的所有操作都勾选,这样可以对数据区域进行插入删除行列等操作,除了不能操作公式区域。
4、公式隐藏,数据不能更改
5、撤消工作表保护即可编辑公式区(有密码需输入密码)
需要修改公式,撤销工作表保护。
二、VBA代码
VBA代码实则是将上面的一系列操作转换为代码。
我们可以将上面的操作录制成一个宏,代码如下:
Sub 宏2()
'
' 宏2 宏
'
'
Range("A1:C4").Select
Selection.Locked = False
Selection.FormulaHidden = False
Range("C1:C4").Select
Selection.Locked = True
Selection.FormulaHidden = True
ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= _
False, AllowFormattingCells:=True, AllowFormattingColumns:=True, _
AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows _
:=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, _
AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, _
AllowUsingPivotTables:=True
ActiveSheet.Unprotect
End Sub
因可能需要重复操作,可将代码修改如下。
Sub 宏2()
On Error Resume Next
With ActiveSheet
.Unprotect '解除工作表保护(无密码)
.UsedRange.Locked = False '解除已用数据区域的锁定属性
.UsedRange.FormulaHidden = False '解除已用数据区域的隐藏公式属性
With ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas, 23) '选取公式区
.Locked = True '锁定公示区
.FormulaHidden = True '隐藏公式
End With
End With
'//保护工作表,允许数据区域的所有操作
ActiveSheet.Protect , DrawingObjects:=False, Contents:=True, Scenarios:= _
False, AllowFormattingCells:=True, AllowFormattingColumns:=True, _
AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows _
:=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, _
AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, _
AllowUsingPivotTables:=True
End Sub
如果需要编辑数据区域外的单元格,撤销保护工作表。