[英]How to Lock the data in a cell containing formulas so that they cannot be edited in excel using vba
[英]How to Lock the data in a cell in excel using vba
我想阻止其他人使用VBA编辑我的Excel工作表中的单元格内容。 是否有可能做到这一点?
您可以通过将它们的锁定状态设置为False来首先选择您不希望受保护的单元格(用户可编辑):
Worksheets("Sheet1").Range("B2:C3").Locked = False
然后,您可以保护工作表,并保护所有其他单元格。 执行此操作的代码仍然允许您的VBA代码修改单元格:
Worksheets("Sheet1").Protect UserInterfaceOnly:=True
要么
Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)
尝试使用Worksheet.Protect
方法,如下所示:
Sub ProtectActiveSheet()
Dim ws As Worksheet
Set ws = ActiveSheet
ws.Protect DrawingObjects:=True, Contents:=True, _
Scenarios:=True, Password="SamplePassword"
End Sub
但是,您应该担心在VBA代码中包含密码。 如果您只想设置一个简单的屏障来防止用户犯下删除公式等错误,那么您不一定需要密码。
此外,如果您想在Excel中查看如何在VBA中执行某些操作,请尝试录制宏并查看它生成的代码。 这是开始使用VBA的好方法。
比方说,例如,在一种情况下,如果要锁定从A1到I50的单元格,那么下面是代码:
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"
在另一种情况下,如果您已经有受保护的工作表,请按照以下代码:
ActiveSheet.Unprotect Password:="Enter your Password"
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"
Sub LockCells()
Range("A1:A1").Select
Selection.Locked = True
Selection.FormulaHidden = False
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
您也可以在工作表的更改事件中捕获的工作表级别上执行此操作。 如果能满足您的需求。 允许基于值,标准等动态锁定...
Private Sub Worksheet_Change(ByVal Target As Range)
'set your criteria here
If Target.Column = 1 Then
'must disable events if you change the sheet as it will
'continually trigger the change event
Application.EnableEvents = False
Application.Undo
Application.EnableEvents = True
MsgBox "You cannot do that!"
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.