①まずは、thisworkbookに下記コードを張り付け
Private Sub Workbook_Open()
Call SecretProtect
End Sub
➁モジュール1に以下貼り付け
Option Explicit
Public Sub SecretProtect()
On Error GoTo ManualExecution
' ▼自動実行か判定
If Application.Caller = "" Then
' 自動実行時のみ処理を行う
Call RealProtectProcess
End If
Exit Sub
ManualExecution:
' エラー時の処理 (メッセージを表示せず、ただ終了する)
Exit Sub
End Sub
Public Sub RealProtectProcess()
Dim ws As Worksheet
Dim hiddenSheet As Worksheet
Dim cell As Range
Dim t As Double
' 開始時間を記録
t = Timer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set ws = ThisWorkbook.Sheets("") '任意のシート名
' 設定用の隠しシートがなければ作成
On Error Resume Next
Set hiddenSheet = ThisWorkbook.Sheets("HiddenConfig")
On Error GoTo 0
If hiddenSheet Is Nothing Then
Set hiddenSheet = ThisWorkbook.Sheets.Add(After:=ws)
With hiddenSheet
.Name = "HiddenConfig"
.Visible = xlSheetVeryHidden
.Range("A1").Value = "設定データ"
End With
End If
' シート保護解除
ws.Unprotect Password:="mypassword"
' 全体ロック+数式表示ONに戻す
ws.Cells.Locked = True
ws.Cells.FormulaHidden = False
' 関数が入っているセルを検索して非表示&ロック
For Each cell In ws.UsedRange
If cell.HasFormula Then
cell.Locked = True
cell.FormulaHidden = True
End If
Next cell
' 入力セルは解除(例: B1:B10)
With ws.Range("B1:B10")
.Locked = False
.FormulaHidden = False
End With
' 保護再設定
ws.Protect Password:="mypassword", UserInterfaceOnly:=True
Application.ScreenUpdating = True
Application.DisplayAlerts = True
' 処理時間を出力
Debug.Print "SecretProtect 実行時間: " & Format(Timer - t, "0.000") & " 秒"
End Sub