【问题标题】:Excel 2013 stop working when using VBA to lock/unlock cell [duplicate]使用VBA锁定/解锁单元格时Excel 2013停止工作[重复]
【发布时间】:2018-07-02 14:00:52
【问题描述】:

我在使用 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

【问题讨论】:

  • 添加以解决问题,但没有帮助。

标签: vba excel locking cell


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    相关资源
    最近更新 更多