2017-02-25 196 views
0

我的Excel VBA解鎖所需的單元格,但在條件更改時無法重新鎖定。鎖定/解鎖變量單元格

在我的Excel實用程序中,如果A1的值爲「A」,那麼它將在範圍A8:A13中找到B1,並解鎖行值爲B1,列值爲「b」且列值爲「c」(這裏單元格B9和C9被解鎖)。我的VBA在這裏工作,但是當我改變B1的值(例如「w」到「e」)時,它再次解鎖相應的單元,例如單元B10和C10,但它不會重新鎖定早先解鎖的單元,即單元B9和C9, 。

Excel utility

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 

回答

1

改變代碼如下:

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