检测整个工作表中的任何(整个)行选择并取消保护?

时间:2013-01-30 16:09:39

标签: excel vba

寻找以下代码:

工作表当前已锁定(已启用锁定单元格选择)。

VBA检测是否有任何整行表示21,22被选中并自动取消保护工作表。

THEN:

如果这些确切的行被删除..工作表会自动再次保护。

如果用户取消选择这些行..工作表再次保护。

(这是执行特定行删除的设计)

非常粗暴地说:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    IF Rows("1:1").Select AND/OR Rows("2:2").Select AND/OR Rows("3:3").Select then
        ActiveSheet.Unprotect
    End If

    ActiveCell.Row.Delete
    ActiveSheet.Protect

End Sub

1 个答案:

答案 0 :(得分:1)

请务必先设置Application.enableEvents = True

编辑在讨论中将代码更改为OP的新规范

限制:整个行(必须解锁每个单元格以便能够选择整行)

' remember the event's name is `Worksheet_SelectionChange`
' NOT Worksheet1_SelectionChange
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    ActiveSheet.Unprotect
    ' the rows to be selected
    Dim row1 As Range
    Dim row2 As Range
    Dim row3 As Range
    Dim mergedRange As Range
    Set row1 = Me.Rows("1:1")
    Set row2 = Me.Rows("3:3")
    Set row3 = Me.Rows("5:5")
    Dim found As Boolean
    Dim Match As Boolean
    Set mergedRange = Application.Union(row1, row2)
    Set mergedRange = Application.Union(mergedRange, row3)
    Match = False


    ' check if it selects only 1 row
    If Target.Areas.Count <> 1 Then
        ActiveSheet.Protect
        Exit Sub
    End If


    ' check if it's select the first 500 rows
    If Target.Areas.Item(1).Row > 0 And Target.Areas.Item(1).Row <= 500 Then
        'check if it's selecting the WHOLE row
        If Me.Rows(Target.Areas.Item(1).Row & ":" & Target.Areas.Item(1).Row).Areas.Item(1).Count = Target.Areas.Item(1).Count Then
            ' check if the "B" Column of this row's backgound color is blue
            If Me.Cells(Target.Areas.Item(1).Row, 2).Interior.Color = RGB(197, 217, 241) Then
                Match = True
            End If
        End If
    End If


    If Match Then

        'MsgBox "ActiveSheet.Unprotect"
        ActiveSheet.Unprotect
    Else
        Debug.Print "notMatch"
        'ActiveCell.Row.Delete
       ActiveSheet.Protect
    End If


End Sub