Check if workbook is protected in Excel Add-in code example

Check if workbook is protected in Excel Add-in code example

Protect Workbook

To prevent other users from viewing hidden worksheets, adding, moving, deleting, or hiding worksheets, and renaming worksheets, you can protect the structure of your Excel workbook with a password.

Problem statement

Consider you are shipping your own Excel template which you ship with protected mode and certainly you created your own password to open it. While checking if workbook that you are accessing through code is protected using your own password? otherwise your code will fall, if it encounter any other file having different protection password.

C# code example

public static bool IsWorkbookProtected(Excel.Workbook wb, string passCode)
{
	try
	{
		wb.Unprotect(passCode);
		return true;
	}
	catch(Exception ex)
	{
		Console.WriteLine("The file is protected");
		return false;
	}
}

VBA code example

Public Function CheckWorkbookProtection(wk As Workbook, oPassword As String) As Boolean
    CheckWorkbookProtection = False
    On Error GoTo errh
    
    'Try unprotecting workbook
    wk.Unprotect oPassword
    
    'exist function with success
    CheckWorkbookProtection = True
errh:
    If Err.Number <> 0 Then
        Exit Function
    End If
End Function

Above method will return true/false by which you can validate your protection.

Next >> How to edit protected sheet in Excel? code example

Leave a Reply

Your email address will not be published. Required fields are marked *