从 Excel 2003 升级到 2007 会导致“堆栈溢出错误” 在以前工作的vba上
以下 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
The following VBA code works great in Excel 2003, but results in a Stack Overflow Error in Excel 2007. The code is required to either unlock or lock certain cells based on a drop-down menu selection. I need to be able to run the code in both Excel 2003 and 2007. Please help.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
堆栈溢出几乎肯定来自递归。 不确定为什么在 Excel 2003 中没有出现堆栈溢出 - 也许是在堆栈溢出之前引发了错误。
您可以防止无限递归,如下所示:
The stack overflow almost certainly comes from recursion. Not sure why you aren't getting a stack overflow in Excel 2003 - perhaps an error is being raised before the stack overflows.
You can protect against infinite recursion something like the following:
每当工作表中的任何单元格发生更改时,您的方法都会被调用。 您的“NO”块会更改目标单元格的内容,从而导致再次调用该方法。
选项:
测试“目标”值,看看它是否是 E28,如果这是您想要捕获的单元格更改。 类似的东西
如果目标.地址<> "$E$28" 然后 Exit Sub
Your method gets called whenever ANY cell in the worksheet changes. Your "NO" block changes the contents of the target cells, which causes the method to be called again.
Options:
Test the "Target" value to see if it's E28, if that's the cell change you want to capture. Something like
If Target.Address <> "$E$28" Then Exit Sub