我在使用VBA脚本根据其他单元格值锁定/解锁单元格时遇到Excel 2013崩溃问题。你能帮我找出我的VBA代码中的错误/错误吗?
Private Sub Worksheet_Change(ByVal Target As Range)
Unprotect "****"
On Error Resume Next
If [S9] = "Yes" Then
Unprotect "****"
[T9].Locked = False
Protect "****"
Else
Unprotect "****"
[T9].Locked = True
[T9].ClearContents
Protect "****"
End If
If [S11] = "Yes" Then
Unprotect "****"
[T11].Locked = False
Protect "****"
Else
Unprotect "****"
[T11].Locked = True
[T11].ClearContents
Protect "****"
End If
Protect "****"
End Sub
答案 0 :(得分:1)
根据导致Worksheet_Change
被触发的情况,我可以看到许多可能出错的内容。尝试下面的重构代码(应该设计)处理大多数不良问题:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Select Case Target.Address 'only do this for particular cells, ignore other cell changes
Case Is = "$S$9", "$S$11" 'case statement because same pattern exists for both cells
Unprotect "****"
If Target.Value = "YES" Then
Target.Offset(, 1).Locked = False
Else
With Target.Offset(, 1)
Application.EnableEvents = False 'so code does not fire an infinite loop
.ClearContents
Application.EnableEvents = True
.Locked = True
End With
End If
Protect "****"
End Select
End Sub