0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VBA ファイルを開いたときに自動で関数を非表示にする

Posted at

①まずは、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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?