0

以下 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
4

2 回答 2

2

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:

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
于 2008-12-08T17:28:26.547 回答
0

每当工作表中的任何单元格发生更改时,都会调用您的方法。您的“否”块会更改目标单元格的内容,从而导致再次调用该方法。

选项:

  1. 按照乔的建议使用标志变量,看看你是否已经在执行
  2. 测试“目标”值以查看它是否为 E28,如果这是您要捕获的单元格更改。就像是

    如果 Target.Address <> "$E$28" 然后退出 Sub

于 2008-12-08T18:20:57.937 回答