简体   繁体   English

锁定/解锁可变单元格

[英]Lock/unlock a variable cell(s)

My Excel VBA unlocks the desired cells but can not relock when criteria changes. My Excel VBA会解锁所需的单元格,但在条件更改时无法重新锁定。

In my Excel utility, if A1 has value "A", then it will find B1 in the range A8:A13 and unlock the cells of the row having value of B1 and column having value "b" and column having value "c" (Here cells B9 and C9 to be unlocked). 在我的Excel实用程序中,如果A1的值为“ A”,则它将在范围A8:A13中找到B1并解锁具有值B1的行和具有值“ b”的列以及具有值“ c”的列的单元格(此处的单元格B9和C9将被解锁)。 My VBA works here but when I change the value of B1 (eg "w" to "e" it again unlock the corresponding cells eg cells B10 and C10 but it does not relock the cells unlocked earlier ie cells B9 and C9. They remains unlocked. 我的VBA在这里工作,但是当我将B1的值(例如,“ w”更改为“ e”)时,它会再次解锁相应的单元格(例如,单元格B10和C10),但不会重新锁定之前解锁的单元格(即,单元格B9和C9)。 。

Excel实用程序

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If [A1] = "A" Then
    ActiveSheet.Unprotect ("")
    [=INDEX(A8:F13,MATCH(B1,A8:A13,0),MATCH("b",A8:F8,0))].Locked = False
    [=INDEX(A8:F13,MATCH(B1,A8:A13,0),MATCH("c",A8:F8,0))].Locked = False
    ActiveSheet.Protect ("")
Else
    ActiveSheet.Unprotect ("")
    [=INDEX(A8:F13,MATCH(B1,A8:A13,0),MATCH("b",A8:F8,0))].Locked = True
    [=INDEX(A8:F13,MATCH(B1,A8:A13,0),MATCH("c",A8:F8,0))].Locked = True
    ActiveSheet.Protect ("")
End If
End Sub

change code to this: 将代码更改为此:

Private Sub Worksheet_Change(ByVal Target As Range)
    If [A1] = "A" Then
        Unprotect ""
        Range("B9:F13").Locked = True '<--|| set all range "locked" 
        [=INDEX(A8:F13,MATCH(B1,A8:A13,0),MATCH("b",A8:F8,0))].Locked = False '<--| unlock wanted cell
        [=INDEX(A8:F13,MATCH(B1,A8:A13,0),MATCH("c",A8:F8,0))].Locked = False '<--| unlock wanted cell
        Protect ""
    End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM