1

寻找以下代码:

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

VBA 检测是否选择了任何整行(例如 21、22)并自动取消保护工作表。

然后:

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

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

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

非常粗略:

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
4

1 回答 1

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
于 2013-01-31T09:21:59.777 回答