如何使用vba在Excel中locking单元格中的数据
我想阻止其他人使用VBA编辑Excel工作表中的单元格内容。 是否有可能做到这一点?
您可以首先通过将其locking状态设置为False来select哪些单元格不受保护(用户可编辑):
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代码中包含密码。 如果您只是试图build立一个简单的屏障来防止用户发生像删除公式等小错误,那么您不一定需要密码。
另外,如果你想看看如何在Excel中的VBA中做某些事情,请尝试录制一个macros,看看它生成的代码。 这是VBA入门的好方法。
比如说,在一种情况下,如果你想locking范围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"
您也可以在工作表更改事件中捕获的工作表级别上执行此操作。 如果那套房你的需求更好。 允许基于值,标准等dynamiclocking…
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
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