Worksheet.Protect AllowDeletingRows 不允许删除行

M.S*_*alk 5 excel vba

在我的工作簿中,我使用以下代码保护 Workbook_Open 上的所有工作表:

ws.Protect Password:="password", UserInterFaceOnly:=True, _
AllowFormattingColumns:=True, AllowFormattingRows:=True, _
AllowInsertingColumns:=True, AllowInsertingRows:=True, _
AllowDeletingColumns:=True, AllowDeletingRows:=True
Run Code Online (Sandbox Code Playgroud)

在最后一行中,我专门打开了AllowDeletingRows 以允许用户删除行。插入行效果很好,但如果我尝试删除受保护工作表上的行,Excel 会告诉我无法删除包含锁定单元格的行。有谁知道如何让AllowDeletingRows正常工作?

Lou*_*uis 0

阅读微软文档

[...]当工作表受保护时,包含要删除的单元格的行必须解锁

这意味着当它们受到保护时,如果您想删除它们,则Sheet必须先解锁。Rows

例子

在此示例中,您可以通过解锁来删除第一个Row(第一行之后)或整个Sheet(第二行之后)。

Sub ProtectionOptions() 
   'Unlock only row 1. 
   Rows("1:1").Locked = False

   'Or Unlock all cells. 
   Cells.Locked = False  

End Sub
Run Code Online (Sandbox Code Playgroud)

编辑

Sub允许您询问用户要删除哪一行,并且您可以设置AllowDeletingRows:=False,因为您不会使用 ExcelDelete函数。这是代码:

Sub Setup()
    ws.Protect Password:="password", UserInterFaceOnly:=True, _
    AllowFormattingColumns:=True, AllowFormattingRows:=True, _
    AllowInsertingColumns:=True, AllowInsertingRows:=True, _
    AllowDeletingColumns:=True, AllowDeletingRows:=False
End Sub

'Connect this Sub to a button.
Sub DeleteRow()
    Dim userInput As String
    Dim row As Long

    userInput = InputBox("Please enter the row number you want to delete:", "Delete Row")
    If Not IsNumeric(userInput) Then
        MsgBox "Provided input is not numeric. Please insert a valid row number", vbExclamation
        Exit Sub
    End If

    row = userInput

    ws.rows(row).Locked = False
    ws.rows(row).Delete

End Sub
Run Code Online (Sandbox Code Playgroud)

注意:此代码经过测试并且可以工作。

希望这可以帮助。