如何使用vba禁用单元格中的更改?

我正在使用以下代码:此代码为例:如果我在单元格A1中input任何值,单元格B1显示一个时间戳。

Private Sub Worksheet_Change(ByVal Target As Excel.Range) With Target If .Count > 1 Then Exit Sub If Not Intersect(Range("B1:B10"), .Cells) Is Nothing Then Application.EnableEvents = False If IsEmpty(.Value) Then .Offset(0, 1).ClearContents Else With .Offset(0, 1) .NumberFormat = "hh:mm AM/PM" .Value = Now End With End If Application.EnableEvents = True End If End With End Sub 

我现在想要做的是保护/不能从用户编辑单元格“B1:B10”,一旦时间戳由macros做出。 我谷歌如何保护,但我很难插入我发现的代码。 任何人都可以帮助我如何构build/插入此代码到我原来的代码?

  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 

或者这个代码:

  'select the cell you want to be editable Worksheets("Sheet1").Range("B2:C3").Locked = False 'then protect the entire sheet but still vba program can modify instead. Worksheets("Sheet1").Protect UserInterfaceOnly:=True 

感谢Kazjaw。 这是最后的代码。

  Private Sub Worksheet_Change(ByVal Target As Excel.Range) 'Protect cell "B1:B10" Worksheets("Sheet1").Cells.Locked = False Worksheets("Sheet1").Range("B1:b10").Locked = True Worksheets("Sheet1").Protect Password:="pass", UserInterfaceOnly:=Tru With Target If .Count > 1 Then Exit Sub If Not Intersect(Range("B1:B10"), .Cells) Is Nothing Then Application.EnableEvents = False If IsEmpty(.Value) Then .Offset(0, 1).ClearContents Else With .Offset(0, 1) .NumberFormat = "hh:mm AM/PM" .Value = Now End With End If Application.EnableEvents = True End If End With End Sub 

如果你只想保护范围B1:B10,那么你只需要运行一次这个子:

 Sub ProtectCellsInB() Worksheets("Sheet1").Cells.Locked = False Worksheets("Sheet1").Range("B1:b10").Locked = True Worksheets("Sheet1").Protect Password:="pass", UserInterfaceOnly:=True End Sub 

我做了修改 – 我添加了一个密码来保护你可以删除。

如果你不知道如何运行一次,那么你可以在Private Sub Worksheet_Change(ByVal Target As Excel.Range)的末尾添加整个内部代码,