用于根据A列中的值锁定和解锁单元格的宏脚本

时间:2018-05-03 11:53:26

标签: excel vba excel-vba excel-2010

我是宏的新手,我正确地根据其他人的价值来锁定和解锁特定的细胞:

Private Sub Worksheet_Change(ByVal Target As range)
    If [$A1] = "Yes" Then
        ActiveSheet.Unprotect ("")
        [$E:$E].locked = True
        [$F:$F].locked = True
        [$N:$N].locked = True
        [$O:$O].locked = True
        [$P:$P].locked = True
        [$X:$X].locked = True
        [$Y:$Y].locked = True
        [$Z:$Z].locked = True
        [$AA:$AA].locked = True
        [$AB:$AB].locked = True
        [$AC:$AC].locked = True
        ActiveSheet.Protect ("")
    Else
        ActiveSheet.Unprotect ("PASSWORD")
        [$E:$E].locked = False
        [$F:$F].locked = False
        [$N:$N].locked = False
        [$O:$O].locked = False
        [$P:$P].locked = False
        [$X:$X].locked = False
        [$Y:$Y].locked = False
        [$Z:$Z].locked = False
        [$AA:$AA].locked = False
        [$AB:$AB].locked = False
        [$AC:$AC].locked = False

        ActiveSheet.Protect ("")
    End If
    If [$A1] = "No" Then
        ActiveSheet.Unprotect ("")
        [$B:$B].locked = True
        ActiveSheet.Protect ("")
    Else
        ActiveSheet.Unprotect ("")
        [$B:$B].locked = False
        ActiveSheet.Protect ("")
    End If
End Sub

$A1我的意思是在A列的所有单元格上运行宏并锁定列范围。

我不知道如何运行和测试,看看是否有任何错误。

编辑:我试过这个但仍然无法测试或看看如何使用它

Private Sub Worksheet_Change(ByVal Target As range)
    If range("A1") = "Yes" Then
        range("B1:B4").locked = True
    ElseIf range("A1") = "No" Then
        range("B1:B4").locked = False
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

首先,例程只有在已经改变的单元格是A1时才有意义 - 我们应该忽略任何其他单元格。

 Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$1" Then
        Dim LockCells As Boolean
        LockCells = (UCase(ActiveSheet.Range("A1")) = "YES")
        Dim ColsToLock
        ColsToLock = Split("E,F,N,O,P,X,Y,Z,AA,AB,AC", ",")
        Dim r As Range
        Dim x As Integer
        ActiveSheet.Unprotect ""
        For x = 0 To UBound(ColsToLock) - 1
            Set r = ActiveSheet.Columns(ColsToLock(x) & ":" & ColsToLock(x))
            r.Locked = LockCells
        Next x
        ActiveSheet.Protect ""


    End If
    End Sub

其次,在开始之前不要忘记取消保护所有单元格