Excel VBA保护工作表而不锁定所有单元格

标签 excel vba

我正在尝试保护 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/

相关文章:

excel - 删除没有颜色的工作表,从所有工作表中删除评论,断开所有源的链接

excel显示在任何列中具有值的行

Excel - 以单元格值作为参数对 SSAS 多维数据集进行 MDX 查询

excel - VBA 中具有多个 IF 和 FOR 语句的 SUMPRODUCT - 错误

VBA:需要关闭窗口,只能关闭工作簿

arrays - 在 Excel VBA 中使用一维或二维数组

vba - PowerPoint VBA 将图像添加到每张幻灯片

excel - 如何在Excel中创建n个单元格

python - 将 df 中的列从另一个列更改为

vba - 运行时错误 '438'