首页 > 解决方案 > Worksheet.Protect AllowDeletingRows 不允许删除行

问题描述

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

ws.Protect Password:="password", UserInterFaceOnly:=True, _
AllowFormattingColumns:=True, AllowFormattingRows:=True, _
AllowInsertingColumns:=True, AllowInsertingRows:=True, _
AllowDeletingColumns:=True, AllowDeletingRows:=True

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

标签: excelvba

解决方案


阅读微软文档

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

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

例子

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

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

   'Or Unlock all cells. 
   Cells.Locked = False  

End Sub

编辑

Sub允许您询问用户要删除的 Row 并且您可以设置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

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

希望这可以帮助。


推荐阅读