excel vba loop - 重复命令直到某个地方

时间:2017-03-22 08:34:54

标签: excel vba excel-vba loops

您好我希望有一个功能,每当我点击某个单元格(E6)时,它会锁定左侧的单元格(A6:C6)或(E7)将锁定(A7:C7)。

Example of my sheet

我真的不知道VBA我只需要这个功能。

我需要为我想要的多个单元格使用它 - 例如每个E2:E1000将锁定左边的行,从A2:C2,A3:C3等等......

Sub ProtectTheSheet()
    Dim chCell As Range
    Dim chRng As Range

    ActiveSheet.Unprotect Password:="password"
    Set chRng = ActiveSheet.Range("A6:C6")

    'Check cell value in body and lock cells with content
    For Each chCell In chRng.Cells
        chCell.Locked = (chCell.Value <> "")
    Next chCell

    ActiveSheet.Protect Password:="password"

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("E6")) Is Nothing Then
            Call ProtectTheSheet
        End If
    End If

End Sub

非常感谢你们。

1 个答案:

答案 0 :(得分:0)

我认为,通过阅读您的问题,下一个代码将解决您的问题:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 And Selection.Column = 5 Then
        ThisWorkbook.ActiveSheet.Unprotect Password:="password"
        For col = 1 To 3
            ThisWorkbook.ActiveSheet.Cells(Selection.Row, col).Locked = True
        Next col
        ThisWorkbook.ActiveSheet.Protect Password:="password"
    End If
End Sub

请注意,在这种情况下,您不需要ProtectTheSheet子例程。