[英]How can I lock cells with formulas?
当我选择保护工作表时,默认情况下我的 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
这是你正在尝试的吗? 我已经对代码进行了注释,因此您理解它应该不会有问题。 但如果你这样做了,那就简单地问一下。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.