我已经阅读了其他几个部分解决了我的问题,但作为一个完整的VB业余爱好者,我无法让它工作。有问题的工作表受到保护,因此尝试在代码中添加protect / unprotect命令。它会在开始时解除保护,但会遇到问题。任何帮助将不胜感激。
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
答案 0 :(得分:2)
您尚未关闭Application.EnableEvents property,但您可能会在工作表中写一些内容。这将重新触发事件处理程序,Worksheet_Change事件宏将尝试在其自身上运行。
没有什么能阻止某人同时清除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 method的 UserInterfaceOnly 参数。将此设置为true允许您在不取消保护工作表的情况下在VBA中执行任何操作。
Addendumm:
如果用户可以更改B11:B12的内容,则不得锁定这些单元格。如果它们没有被锁定,那么在(可能)改变它们的内容之前不需要取消保护工作表。