【问题标题】:How can I lock cells with formulas?如何使用公式锁定单元格?
【发布时间】:2021-01-07 06:04:45
【问题描述】:

当我选择保护工作表时,默认情况下,我的 Excel 会锁定所有列。

我想使用 VBA 代码,我只用公式锁定单元格(并且只允许用户选择未锁定的单元格),同时循环浏览工作簿中的每个工作表。这是我目前拥有的代码。

Sub LockSheets()
    Dim ws As Worksheet
    For Each ws In Worksheets
        With ws
            .Unprotect
            .Cells.Locked = False
            .Cells.SpecialCells(xlCellTypeFormulas).Locked = True
            .Protect
        End With
    Next ws
End Sub

【问题讨论】:

  • 这能回答你的问题吗? How to Lock the data in a cell in excel using vba
  • 阅读SpecialCellsXlCellTypexlCellTypeFormulas,然后只锁定那些单元格。
  • 我试过 .Cells.SpecialCells(xlCellTypeFormulas).Locked = True 但它说没有找到单元格。知道如何解决这个问题吗?
  • 那是因为该特定工作表没有包含公式的单元格? Aso 使用 SpecialCells 时,您必须进行适当的处​​理。发布您尝试过的内容,我们可以从那里获取它
  • 更新了我的代码。我有一些根本没有公式的工作表。我只想保护有公式的工作表。

标签: excel vba


【解决方案1】:

这是你正在尝试的吗?我已经对代码进行了注释,因此您理解它应该没有问题。但如果你这样做了,那就简单地问吧。

Option Explicit

'~~> Change this to the relevant password
Const myPass As String = "MyPassword"

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    
    '~~> Loop through worksheets
    For Each ws In ThisWorkbook.Sheets
        With ws
            Select Case .Name
            '~~> Ignore these sheets
            Case "Navigation", "Template", "Details"
            Case Else
                .Unprotect myPass
                
                .Cells.Locked = False
                
                '~~> Set your range which contains forulas
                On Error Resume Next
                Set rng = .Cells.SpecialCells(xlCellTypeFormulas)
                On Error GoTo 0
                
                '~~> If found then set them locked. This is required
                '~~> because some sheet(s) may not have formulas
                If Not rng Is Nothing Then rng.Locked = True
                
                '~~> Reset to nothing to prevent false results
                Set rng = Nothing
                
                '~~> Protect sheet
                .Protect myPass
                
                '~~> Allow selectiong of only unlocked cells
                .EnableSelection = xlUnlockedCells
            End Select
        End With
    Next ws
End Sub

【讨论】:

  • 谢谢。这种工作,但知道如何编码,这样当我保护时,用户只能选择未锁定的单元格?目前,即使工作表受到保护,用户也可以选择所有单元格。
  • 只需在.Protect myPass 之后添加.EnableSelection = xlUnlockedCells。我已经更新了上面的帖子。您可能需要刷新页面才能看到它
  • 抱歉,最后一个问题。如果我想让第一张工作表不受保护怎么办?
  • With ws 之后添加If Not ws.Name = "RelevantSheetName" Then 并将其余代码放入其中,
  • 我已经更新了答案。刷新以查看它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多