运行时1004解决方法 – 在Worksheet_Change中保护/取消保护

我读过一些其他部分解决了我的问题,但作为一个完整的VB业余爱好者,我不能得到这个工作。 问题中的工作表是受保护的,因此试图在代码中添加一个保护/取消保护命令。 它会在开始时保护好,但遇到问题。 任何帮助,将不胜感激。

Private Sub Worksheet_Change(ByVal Target As Range) Sheet1.Unprotect Password:="mypassword" If Target.Cells.Count > 1 Then Exit Sub If Not Intersect(Target, Range("B11")) Is Nothing Then Select Case Target.Value Case Is = "" Target.Value = "Product Name (IE Product123)" Target.Font.ColorIndex = 15 Case Else Target.Font.ColorIndex = 1 End Select End If If Not Intersect(Target, Range("B12")) Is Nothing Then Select Case Target.Value Case Is = "" Target.Value = "Version " Target.Font.ColorIndex = 15 Case Else Target.Font.ColorIndex = 1 End Select End If Sheet1.Protect Password:="mypassword" End Sub 

您尚未closuresApplication.EnableEvents属性,但有可能会将某些内容写入工作表。 这将重新触发事件处理程序,并且Worksheet_Change事件macros将尝试在其本身之上运行。

没有任何东西阻止某人同时清除B11和B12的内容。 如果目标中有两个单元格,则不是放弃处理,而是调整这个可能性并处理这两个单元格。

 Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Range("B11:B12")) Is Nothing Then On Error GoTo bm_Safe_Exit 'turn off event handling 'cause we might write something Application.EnableEvents = False 'why this unprotect necessary?? 'Me.Unprotect Password:="mypassword" Dim rng As Range For Each rng In Intersect(Target, Range("B11:B12")) Select Case rng.Value2 Case vbNullString If rng.Address(0, 0) = "B11" Then rng = "Product Name (IE Product123)" Else rng = "Version " '<~~ why the trailing space?? End If rng.Font.ColorIndex = 15 Case Else rng.Font.ColorIndex = 1 End Select Next rng End If bm_Safe_Exit: 'if unprotect is not necessary, neither is protect 'Me.Protect Password:="mypassword" Application.EnableEvents = True End Sub 

您可能还想查看Worksheet.Protect方法的UserInterfaceOnly参数。 如果将此设置为true,则可以在不保护工作表的情况下在VBA中执行任何操作。

Addendumm:

如果用户可以改变B11:B12的内容,那么这些单元不能被locking。 如果他们没有locking,那么在(可能)更改他们的内容之前不需要取消保护工作表。