試算表含核心計算公式,分享給同事協作時怕被誤修改導致連鎖錯誤。VBA 掃描全表鎖定所有含公式儲存格,再啟用工作表保護,精準守護邏輯核心,非公式區域仍可自由編輯。
Sub LockFormulaCells()
Dim ws As Worksheet
Dim rngFormulas As Range, cell As Range
Set ws = ActiveSheet
' 1. 解除保護 (若已保護) 以便修改鎖定屬性
On Error Resume Next
ws.Unprotect
On Error GoTo 0
' 2. 先解鎖全表 (預設全鎖定)
ws.Cells.Locked = False
' 3. 找出所有含公式的儲存格
On Error Resume Next
Set rngFormulas = ws.Cells.SpecialCells(xlCellTypeFormulas)
On Error GoTo 0
' 4. 鎖定公式儲存格
If Not rngFormulas Is Nothing Then
rngFormulas.Locked = True
End If
' 5. 啟用工作表保護 (可選設密碼)
ws.Protect Password:="yourpassword", _
UserInterfaceOnly:=True, ' 允許 VBA 操作不受保護限制
AllowFormattingCells:=True, _
AllowFormattingColumns:=True, _
AllowFormattingRows:=True, _
AllowInsertingRows:=True, _
AllowDeletingRows:=True
MsgBox "已鎖定 " & rngFormulas.Count & " 個含公式儲存格,工作表保護啟用。", vbInformation
End Sub




LockFormulaCells →「執行」。UserInterfaceOnly:=True:極重要!讓 VBA 代碼仍可修改受保護儲存格,否則後續巨集會失效。AllowFormattingCells/Columns/Rows:=True:允許使用者調整格式/欄寬/列高,不影響公式邏輯。AllowInserting/DeletingRows:=True:允許插入/刪除列,維持表格擴充彈性。「審閱」→「取消保護工作表」→ 輸入密碼。或 VBA:ActiveSheet.Unprotect "yourpassword"。
鎖定公式儲存格是協作試算表的基本防護,VBA 一鍵部署,讓核心邏輯穩如磐石。