如果相邻单元格为空,则锁定单元格 - Excel VBA

时间:2013-11-27 14:08:36

标签: excel excel-vba vba

我想得到的是,如果“D4:D14”范围内的单元格为空,则相邻单元格被锁定。我的代码如下,但它不起作用:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range

    Set rng = Intersect(Range("D4:D14"), Target)

    If rng Is Nothing Then

    Else
        If IsEmpty(Target) Then
            rng.Offset(0, 1).Locked = True
        Else
            rng.Offset(0, 1).Locked = False
        End If
    End If
End Sub

1 个答案:

答案 0 :(得分:1)

  

我想得到的是,如果“D4:D14”范围内的单元格为空,则相邻单元格将被锁定

在您的代码中,如果单元格为空,则您将.Locked属性设置为False,而我想您想要相反?

这对我有用

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    Dim aCell As Range

    Application.EnableEvents = False

    If Not Intersect(Range("D4:D14"), Target) Is Nothing Then
        ActiveSheet.Unprotect "MYPASSWORD" <~~ Change this to the actual password
        For Each aCell In Range("D4:D14")
            If Len(Trim(aCell.Value)) = 0 Then _
            aCell.Offset(, 1).Locked = True Else _
            aCell.Offset(, 1).Locked = False
        Next
        ActiveSheet.Protect "MYPASSWORD" <~~ Change this to the actual password
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

还要确保工作表受到保护,以查看锁定单元格的效果。

修改

问题的标题是

  

如果相邻单元格为空,则解锁单元格 - Excel VBA

在这种情况下

            If Len(Trim(aCell.Value)) = 0 Then _
            aCell.Offset(, 1).Locked = True Else _
            aCell.Offset(, 1).Locked = False

变为

            If Len(Trim(aCell.Value)) = 0 Then _
            aCell.Offset(, 1).Locked = False Else _
            aCell.Offset(, 1).Locked = True

注意:如果上述代码仍无效,请在立即窗口中输入,然后按输入

Application.EnableEvents = True

enter image description here