我正在尝试保护 Excel 电子表格中的标题。为此,我选择了整个工作表,转到单元格属性,然后取消选中“锁定”。然后,我只选择了第一行并选中了“锁定”。
我的宏一次运行良好,然后再次运行时出现与被锁定的工作表相关的错误,当我回去检查工作表时,现在所有单元格都再次被锁定。我没有任何 VBA 代码指定锁定任何单元格。我运行这个宏来保护床单:
Public Sub ProtectSheet(Optional sheetname As String)
Dim thisSheet As Worksheet
'This is to protect sheet from userinterface, but not from macros
If IsMissing(sheetname) Then sheetname = ""
If sheetname = "" Then
Set thisSheet = ActiveWorkbook.ActiveSheet
Else
Set thisSheet = ActiveWorkbook.Worksheets(sheetname)
End If
thisSheet.Protect UserInterfaceOnly:=False, Contents:=True, DrawingObjects:=True, Scenarios:=True, AllowFormattingRows:=True, AllowFormattingColumns:=True, AllowFormattingCells:=True, AllowInsertingHyperlinks:=True, AllowSorting:=True, AllowFiltering:=True
End Sub
我按如下方式创建了 VBA 代码来取消保护工作表,全选并解锁,然后锁定第一行,然后进行保护。当我这样做时它有效,但我不明白为什么我必须这样做。Public Sub ProtectSheet(Optional sheetname As String)
Dim thisSheet As Worksheet
'This is to protect sheet from userinterface, but not from macros
If IsMissing(sheetname) Then sheetname = ""
If sheetname = "" Then
Set thisSheet = ActiveWorkbook.ActiveSheet
Else
Set thisSheet = ActiveWorkbook.Worksheets(sheetname)
End If
thisSheet.Unprotect
thisSheet.Cells.Locked = False
thisSheet.Rows(1).Locked = True
thisSheet.Protect UserInterfaceOnly:=False, Contents:=True, DrawingObjects:=True, Scenarios:=True, AllowFormattingRows:=True, AllowFormattingColumns:=True, AllowFormattingCells:=True, AllowInsertingHyperlinks:=True, AllowSorting:=True, AllowFiltering:=True
End Sub
我想了解为什么我所有的单元格都被锁定,并且当我认为我不应该添加这个额外的代码时,我不想添加这个额外的代码。 Excel 中是否存在导致锁定属性设置的错误,或者我在此代码中遗漏了自动锁定它们的内容?
最佳答案
如果问题是使用 Clear
然后考虑创建一个单独的子来管理它,并调用它而不是 Clear
.
Sub ClearButUnlocked(rng As Range)
with rng
.clear
.cells.locked=false
end with
end sub
...假设 rng
只有一种锁定状态,而不是锁定/解锁单元格的混合
关于Excel VBA保护工作表而不锁定所有单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67796441/