以下VBA代码在Excel 2003中运行良好,但在Excel 2007中导致堆栈溢出错误。根据下拉菜单选择,需要代码解锁或锁定某些单元格。我需要能够在Excel 2003和2007中运行代码。请帮忙。
Private Sub Worksheet_Change(ByVal Target As Range)
If [E28] = "NO" Then
ActiveSheet.Unprotect ("PASSWORD")
[K47:K53].Locked = False
[K47:K53].Interior.ColorIndex = 16
[K47:K53].ClearContents
ActiveSheet.Protect ("PASSWORD")
Else
ActiveSheet.Unprotect ("PASSWORD")
[K47:K53].Interior.ColorIndex = 0
'Next line is optional, remove preceding apostrophe if protection should stay on.
ActiveSheet.Protect ("PASSWORD")
End If
End Sub
答案 0 :(得分:2)
堆栈溢出几乎肯定来自递归。不确定为什么你没有在Excel 2003中获得堆栈溢出 - 可能在堆栈溢出之前引发错误。
您可以防止无限递归,如下所示:
Private m_bInChange As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
If m_bInChange Then Exit Sub
On Error GoTo ErrHandler
m_bInChange = True
If [E28] = "NO" Then
ActiveSheet.Unprotect ("PASSWORD")
[K47:K53].Locked = False
[K47:K53].Interior.ColorIndex = 16
[K47:K53].ClearContents
ActiveSheet.Protect ("PASSWORD")
Else
ActiveSheet.Unprotect ("PASSWORD")
[K47:K53].Interior.ColorIndex = 0
'Next line is optional, remove preceding apostrophe if protection should stay on.
ActiveSheet.Protect ("PASSWORD")
End If
m_bInChange = False
Exit Sub
ErrHandler:
m_bInChange = False
Exit Sub
End Sub
答案 1 :(得分:0)
只要工作表中的任何单元格发生更改,就会调用您的方法。您的“NO”块会更改目标单元格的内容,从而导致再次调用该方法。
选项:
测试“目标”值以查看它是否为E28,如果这是您要捕获的单元格更改。像
这样的东西如果Target.Address<> “$ E $ 28”然后退出Sub