在我的工作簿中,我使用以下代码保护 Workbook_Open 上的所有工作表:
ws.Protect Password:="password", UserInterFaceOnly:=True, _
AllowFormattingColumns:=True, AllowFormattingRows:=True, _
AllowInsertingColumns:=True, AllowInsertingRows:=True, _
AllowDeletingColumns:=True, AllowDeletingRows:=True
在最后一行中,我专门打开了AllowDeletingRows以允许用户删除行。插入行效果很好,但如果我尝试删除受保护工作表上的行,Excel 会告诉我无法删除包含锁定单元格的行。有谁知道如何让AllowDeletingRows正常工作?
阅读Microsoft 文档:
[...] 当工作表受到“保护”时,包含要删除的单元格的行必须“解锁”。 这意味着当
受到保护时,如果您想删除它们,必须先解锁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
AllowDeletingRows:=False
,因为您不会使用 Excel
Delete
功能。这是代码: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
注意:此代码经过测试并且可以工作。
希望这有帮助。
奇怪的答案;需要取消保护才能删除一行。
AllowDeletingRows:=True我也有同样的问题...