Vba excel if sheet protected

To check for password protection one needs to try to unprotect the sheet and after that to protect it again (if it was not password protected), but at that point it looses all the protection settings the user had made. Like Allow PivotTables, Allow Formatting Cells and so on.
So one has to read the settings of the sheet first and when protecting it, applying the settings again.
Protection also means not only protectcontents but also protectobject and protectscenarios.
And if it is a Chart Sheet, it also needs a different procedure to check.
I spend som hours to create a macro which can do all this for ALL Sheets (even for Chart Sheets).

 Sub Run_CheckSheetPasswordProtection()
    'execudes the Function CheckSheetPasswordProtection
    'to detect if a sheet (Worksheet or Chart Sheet) is protected, password protected or not protected
    'protection setting of that sheet will remain the same after checking (other, simpler, macros will not take car for this)
    
    Dim wb As Workbook
    Dim ws As Variant 'variant is needed to handle Worksheets AND Chart Sheets
    Dim sh As Variant
    
    Set wb = ThisWorkbook 'or use: Workbooks("Name of my Workbook")
    
    '***check one sheet*****
'    'adjust your worksheet you want to test here
'    Set ws = wb.Worksheets("sheet1")
'
'    MsgBox ws.Name & ":     " & CheckSheetPasswordProtection(ws)
    
    
    
    '****check all sheets of a workbook**********
    
    For Each sh In wb.Sheets
        'write ansers to the Immediate Window
        Debug.Print sh.Name & ":     " & CheckSheetPasswordProtection(sh)
    Next sh
End Sub


Function CheckSheetPasswordProtection(YourSheet As Variant) As String
    'check if worksheets are protected with a password
    'doesn't destroy the previous protection settings of that sheet
    Dim ws As Variant
    Dim wb As Workbook
    Dim ProtectionResult As String
    
    'Settings of the sheet
    Dim sDrawingObjects As Boolean
    Dim sContents As Boolean
    Dim sScenarios As Boolean
    Dim sUserInterfaceOnly As Boolean
    Dim sAllowFormattingCells As Boolean
    Dim sAllowFormattingColumns As Boolean
    Dim sAllowFormattingRows As Boolean
    Dim sAllowInsertingColumns As Boolean
    Dim sAllowInsertingRows As Boolean
    Dim sAllowInseringHyperlinks As Boolean
    Dim sAllowDeletingColumns As Boolean
    Dim sAllowDeletingRows As Boolean
    Dim sAllowSorting As Boolean
    Dim sAllowFiltering As Boolean
    Dim sAllowUsingPivotTables As Boolean
    Dim sEnableSelection As Integer ' 0   Anything can be selected, -4142   Nothing can be selected, 1   Only unlocked cells can be selected.
    Dim sEnableOutlining As Boolean
    
    Set ws = YourSheet
    
    
        '***********if it is a worksheet**************
        If TypeName(ws) = "Worksheet" Then
        
            'check protection settings of the sheet
            sDrawingObjects = ws.ProtectDrawingObjects
            sContents = ws.ProtectContents
            sScenarios = ws.ProtectScenarios
            sUserInterfaceOnly = ws.ProtectionMode
            sAllowFormattingCells = ws.Protection.AllowFormattingCells
            sAllowFormattingColumns = ws.Protection.AllowFormattingColumns
            sAllowFormattingRows = ws.Protection.AllowFormattingRows
            sAllowInsertingColumns = ws.Protection.AllowInsertingColumns
            sAllowInsertingRows = ws.Protection.AllowInsertingRows
            sAllowInseringHyperlinks = ws.Protection.AllowInsertingHyperlinks
            sAllowDeletingColumns = ws.Protection.AllowDeletingColumns
            sAllowDeletingRows = ws.Protection.AllowDeletingRows
            sAllowSorting = ws.Protection.AllowSorting
            sAllowFiltering = ws.Protection.AllowFiltering
            sAllowUsingPivotTables = ws.Protection.AllowUsingPivotTables
            sEnableSelection = ws.EnableSelection
            sEnableOutlining = ws.EnableOutlining
            
            If ws.ProtectContents Or ws.ProtectDrawingObjects Or ws.ProtectScenarios Then
                ProtectionResult = "Protected"
            
                On Error Resume Next
                ws.Unprotect Password:=""
                If Err.Number > 0 Then
                    ProtectionResult = "PASSWORD protected"
                Else 'if sheet was not protected with password, protect it again with its previous setting
                    ws.Protect _
                    Password:="", _
                    DrawingObjects:=sDrawingObjects, _
                    Contents:=sContents, _
                    Scenarios:=sScenarios, _
                    AllowFormattingCells:=sAllowFormattingCells, _
                    AllowFormattingColumns:=sAllowFormattingColumns, _
                    AllowFormattingRows:=sAllowFormattingRows, _
                    AllowInsertingColumns:=sAllowInsertingColumns, _
                    AllowInsertingRows:=sAllowInsertingRows, _
                    AllowInsertingHyperlinks:=sAllowInseringHyperlinks, _
                    AllowDeletingColumns:=sAllowDeletingColumns, _
                    AllowDeletingRows:=sAllowDeletingRows, _
                    AllowSorting:=sAllowSorting, _
                    AllowFiltering:=sAllowFiltering, _
                    AllowUsingPivotTables:=sAllowUsingPivotTables, _
                    UserInterfaceOnly:=sUserInterfaceOnly
                
                    ws.EnableSelection = sEnableSelection
                    ws.EnableOutlining = sEnableOutlining
                End If 'checking for password (error)
                On Error GoTo 0
            Else 'if worksheet is not protected
                ProtectionResult = "No Protection"
            End If 'if protected
            
        
        Else '*************if it is a chart*************** If TypeName(ws) = "Chart"
            'check protection settings of the sheet
            sDrawingObjects = ws.ProtectDrawingObjects
            sContents = ws.ProtectContents
            
            'if chart is protected
            If ws.ProtectContents Or ws.ProtectDrawingObjects Then
                ProtectionResult = "Protected"
            
                On Error Resume Next
                ws.Unprotect Password:=""
                If Err.Number > 0 Then
                    ProtectionResult = "PASSWORD protected"
                Else 'if sheet was not protected with password, protect it again with its previous setting
                    ws.Protect _
                    Password:="", _
                    DrawingObjects:=sDrawingObjects, _
                    Contents:=sContents
                End If 'checking for password (error)
                On Error GoTo 0
            Else 'if worksheet is not protected
                ProtectionResult = "No Protection"
            End If 'if protected
            
        
        End If 'Worksheet or Chart
        CheckSheetPasswordProtection = ProtectionResult

End Function

Excel Spreadsheet Protection

Detecting Sheet Protection

I can’t count how many times I have been completely confused while working in somebody else’s spreadsheet only to discover my issue was being caused due to a spreadsheet being protected (it’s even worse with the spreadsheet is hidden). Let’s review some ways you can quickly figure out if you have sheets protected in your workbook.

Sheet Icon (New for 2020!)

This is an exciting little feature that got released in May 2020 via the Insider version of Excel (aka public beta version). Any time a worksheet has protection enabled, a padlock icon shows in front of the tab name. This is a great little indicator to easily understand if a worksheet is protected or not. I suspect this handy little feature will hit the monthly channel in a couple of months as long as they do not find any issues with it.

Excel Password Icon Tab Name

My Wish List: Unfortunately, as of this writing, the padlock icon does not appear within the Unhide dialog, but I sent a little mockup to Microsoft and suggested it (shown below).

Unhide Dialog With Padlock Icon

Unprotect Button Appears

If you suspect the sheet you are viewing is protected, you can navigate to the Review tab on your Excel Ribbon and checkout the Protect buttons. If the first button’s name is Unprotect Sheet, you know your ActiveSheet is currently protected.

Unprotect vs Protect Button Excel Ribbon

Disabled Ribbon Buttons

Another way to infer there might be some sort of sheet protection enabled is if you notice many of your buttons on your Excel Ribbon are disabled. Notice in the example below how nearly any button that deals with formatting is grayed out on the Home tab.

Disabled Excel Ribbon Buttons

Disabled Menu Buttons

Similar to buttons in your Ribbon being disabled, sheet protection can also causing menu you buttons to become disabled when you right-click. If you notice a bunch of your buttons grayed out, chances are theirs some sort of sheet protection that has been activated.

Disabled Excel Menu Items

Use VBA To Display A List

You can also utilize VBA code to perform tests or even provide a summary list of any protected sheets within your workbook.

Below is a simple function called IsProtected that provides a True/False result for the worksheet object that is passed through it.

Function IsProtected(sht As Worksheet) As Boolean
‘PURPOSE: Determine if a specific Sheet has protection enabled

‘Test if Sheet is Protected (T/F)
  IsProtected = sht.ProtectContents

End Function

You could also write a more versatile VBA macro that searches through all the tabs in your ActiveWorkbook and summarizes any protection found.

Sub SheetProtectionSummary()
‘PURPOSE: List out all sheets that have protection enabled
‘SOURCE: www.thespreadsheetguru.com/the-code-vault

Dim sht As Worksheet
Dim VisibleSheetList As String
Dim HiddenSheetList As String

‘Loop through each sheet and test for protection
  For Each sht In ActiveWorkbook.Worksheets

      If sht.ProtectContents = True Then
      If sht.Visible = xlSheetVisible Then
        VisibleSheetList = VisibleSheetList & vbNewLine & »  — » & sht.Name
      Else
        HiddenSheetList = HiddenSheetList & vbNewLine & »  — » & sht.Name
      End If
    End If

    Next sht

‘Display Results
  If HiddenSheetList = «» And VisibleSheetList = «» Then
    MsgBox «No worksheets were found to currently be protected in this workbook»
  Else
    MsgBox «The following worksheets were found to have sheet protection enabled:» & _
      vbNewLine & vbNewLine & «Visble Worksheets:» & VisibleSheetList & _
      vbNewLine & vbNewLine & «Hidden Worksheets:» & HiddenSheetList, , «Protection Summary»
  End If

End Sub

After running this macro on a Workbook, you can see the results displayed in a message box (shown below). You’ll notice that in this particular VBA code, I’ve grouped the protected sheet name results depending on if they are hidden to the user or not.

Protection Summary VBA Message Box

I Hope This Helped!

Hopefully, I was able to explain how you can determine is a sheet in Excel is protected or unprotected. If you have any questions about this technique or suggestions on how to improve it, please let me know in the comments section below.

Chris Newman 2020 - TheSpreadsheetGuru

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you some value today and hope to see you back here soon! — Chris

Protecting and unprotecting sheets is a common action for an Excel user. There is nothing worse than when somebody, who doesn’t know what they’re doing, overtypes essential formulas and cell values. It’s even worse when that person happens to be us; all it takes is one accidental keypress, and suddenly the entire worksheet is filled with errors. In this post, we explore using VBA to protect and unprotect sheets.

Protection is not foolproof but prevents accidental alteration by an unknowing user.

Sheet protection is particularly frustrating as it has to be applied one sheet at a time. If we only need to protect a single sheet, that’s fine. But if we have more than 5 sheets, it is going to take a while. This is why so many people turn to a VBA solution.

The VBA Code Snippets below show how to do most activities related to protecting and unprotecting sheets.

Download the example file: Click the link below to download the example file used for this post:

Adapting the code for your purposes

Unless stated otherwise, every example below is based on one specific worksheet. Each code includes Sheets(“Sheet1”)., this means the action will be applied to that specific sheet. For example, the following protects Sheet1.

Sheets("Sheet1").Protect

But there are lots of ways to reference sheets for protecting or unprotecting. Therefore we can change the syntax to use one of the methods shown below.

Using the active sheet

The active sheet is whichever sheet is currently being used within the Excel window.

ActiveSheet.Protect

Applying a sheet to a variable

If we want to apply protection to a sheet stored as a variable, we could use the following.

Dim ws As Worksheet

Set ws = Sheets("Sheet1")

ws.Protect

Later in the post, we look at code examples to loop through each sheet and apply protection quickly.

Let’s begin with some simple examples to protect and unprotect sheets in Excel.

Protect a sheet without a password

Sub ProtectSheet()

'Protect a worksheet
Sheets("Sheet1").Protect

End Sub

Unprotect a sheet (no password)

Sub UnProtectSheet()

'Unprotect a worksheet
Sheets("Sheet1").Unprotect

End Sub

Protecting and unprotecting with a password

Adding a password to give an extra layer of protection is easy enough with VBA. The password in these examples is hardcoded into the macro; this may not be the best for your scenario. It may be better to apply using a string variable, or capturing user passwords with an InputBox.

VBA Protect sheet with password

Sub ProtectSheetWithPassword()

'Protect worksheet with a password
Sheets("Sheet1").Protect Password:="myPassword"

End Sub

VBA Unprotect sheet with a password

Sub UnProtectSheetWithPassword()

'Unprotect a worksheet with a password
Sheets("Sheet1").Unprotect Password:="myPassword"

End Sub

NOTE – It is not necessary to unprotect, then re-protect a sheet to change the settings. Instead, just protect again with the new settings.

Using a password based on user input

Using a password that is included in the code may partly defeat the benefit of having a password. Therefore, the codes in this section provide examples of using VBA to protect and unprotect based on user input. In both scenarios, clicking Cancel is equivalent to entering no password.

Protect with a user-input password

Sub ProtectSheetWithPasswordFromUser()

'Protect worksheet with a password
Sheets("Sheet1").Protect Password:=InputBox("Enter a protection password:")

End Sub

Unprotect with a user-input password

Sub UnProtectSheetWithPasswordFromUser()

'Protect worksheet with a password
Sheets("Sheet1").Unprotect _
    Password:=InputBox("Enter a protection password:")

End Sub

Catching errors when incorrect password entered

If an incorrect password is provided, the following error message displays.

VBA to protect and unprotect sheets - Incorrect password

The code below catches the error and provides a custom message.

Sub CatchErrorForWrongPassword()

'Keep going even if error found
On Error Resume Next

'Apply the wrong password
Sheets("Sheet1").Unprotect Password:="incorrectPassword"

'Check if an error has occured
If Err.Number <> 0 Then
    MsgBox "The Password Provided is incorrect"
    Exit Sub
End If

'Reset to show normal error messages
On Error GoTo 0

End Sub

If you forget a password, don’t worry, the protection is easy to remove.

Applying protection to different parts of the worksheet

VBA provides the ability to protect 3 aspects of the worksheet:

  • Contents – what you see on the grid
  • Objects – the shapes and charts which are on the face of the grid
  • Scenarios – the scenarios contained in the What If Analysis section of the Ribbon

By default, the standard protect feature will apply all three types of protection at the same time. However, we can be specific about which elements of the worksheet are protected.

Protect contents

Sub ProtectSheetContents()

'Apply worksheet contents protection only
Sheets("Sheet1").Protect Password:="myPassword", _
    DrawingObjects:=False, _
    Contents:=True, _
    Scenarios:=False

End Sub

Protect objects

Sub ProtectSheetObjects()

'Apply worksheet objects protection only
Sheets("Sheet1").Protect Password:="myPassword", _
    DrawingObjects:=True, _
    Contents:=False, _
    Scenarios:=False

End Sub

Protect scenarios

Sub ProtectSheetScenarios()

'Apply worksheet scenario protection only
Sheets("Sheet1").Protect Password:="myPassword", _
    DrawingObjects:=False, _
    Contents:=False, _
    Scenarios:=True

End Sub

Protect contents, objects and scenarios

Sub ProtectSheetAll()

'Apply worksheet protection to contents, objects and scenarios
Sheets("Sheet1").Protect Password:="myPassword", _
    DrawingObjects:=True, _
    Contents:=True, _
    Scenarios:=True

End Sub

Applying protection to multiple sheets

As we have seen, protection is applied one sheet at a time. Therefore, looping is an excellent way to apply settings to a lot of sheets quickly. The examples in this section don’t just apply to Sheet1, as the previous examples have, but include all worksheets or all selected worksheets.

Protect all worksheets in the active workbook

Sub ProtectAllWorksheets()

'Create a variable to hold worksheets
Dim ws As Worksheet

'Loop through each worksheet in the active workbook
For Each ws In ActiveWorkbook.Worksheets

    'Protect each worksheet
    ws.Protect Password:="myPassword"

Next ws

End Sub

Protect the selected sheets in the active workbook

Sub ProtectSelectedWorksheets()

Dim ws As Worksheet
Dim sheetArray As Variant

'Capture the selected sheets
Set sheetArray = ActiveWindow.SelectedSheets

'Loop through each worksheet in the active workbook
For Each ws In sheetArray

    On Error Resume Next

    'Select the worksheet
    ws.Select

    'Protect each worksheet
    ws.Protect Password:="myPassword"

    On Error GoTo 0

Next ws

sheetArray.Select

End Sub

Unprotect all sheets in active workbook

Sub UnprotectAllWorksheets()

'Create a variable to hold worksheets
Dim ws As Worksheet

'Loop through each worksheet in the active workbook
For Each ws In ActiveWorkbook.Worksheets

'Unprotect each worksheet
ws.Unprotect Password:="myPassword"

Next ws

End Sub

Checking if a worksheet is protected

The codes in this section check if each type of protection has been applied.

Check if Sheet contents is protected

Sub CheckIfSheetContentsProtected()

'Check if worksheets contents is protected
If Sheets("Sheet1").ProtectContents Then MsgBox "Protected Contents"

End Sub

Check if Sheet objects are protected

Sub CheckIfSheetObjectsProtected()

'Check if worksheet objects are protected
If Sheets("Sheet1").ProtectDrawingObjects Then MsgBox "Protected Objects"

End Sub

Check if Sheet scenarios are protected

Sub CheckIfSheetScenariosProtected()

'Check if worksheet scenarios are protected
If Sheets("Sheet1").ProtectScenarios Then MsgBox "Protected Scenarios"

End Sub

Changing the locked or unlocked status of cells, objects and scenarios

When a sheet is protected, unlocked items can still be edited. The following codes demonstrate how to lock and unlock ranges, cells, charts, shapes and scenarios.

When the sheet is unprotected, the lock setting has no impact. Each object becomes locked on protection.

All the examples in this section set each object/item to lock when protected. To set as unlocked, change the value to False.

Lock a cell

Sub LockACell()

'Changing the options to lock or unlock cells
Sheets("Sheet1").Range("A1").Locked = True

End Sub

Lock all cells

Sub LockAllCells()

'Changing the options to lock or unlock cells all cells
Sheets("Sheet1").Cells.Locked = True

End Sub

Lock a chart

Sub LockAChart()

'Changing the options to lock or unlock charts
Sheets("Sheet1").ChartObjects("Chart 1").Locked = True

End Sub

Lock a shape

Sub LockAShape()

'Changing the option to lock or unlock shapes
Sheets("Sheet1").Shapes("Rectangle 1").Locked = True

End Sub

Lock a Scenario

Sub LockAScenario()

'Changing the option to lock or unlock a scenario
Sheets("Sheet1").Scenarios("scenarioName").Locked = True

End Sub

Allowing actions to be performed even when protected

Even when protected, we can allow specific operations, such as inserting rows, formatting cells, sorting, etc. These are the same options as found when manually protecting the sheet.

Standard protection settings

Allow sheet actions when protected

Sub AllowSheetActionsWhenProtected()

'Allowing certain actions even if the worksheet is protected
Sheets("Sheet1").Protect Password:="myPassword", _
    DrawingObjects:=False, _
    Contents:=True, _
    Scenarios:=False, _
    AllowFormattingCells:=True, _
    AllowFormattingColumns:=True, _
    AllowFormattingRows:=True, _
    AllowInsertingColumns:=False, _
    AllowInsertingRows:=False, _
    AllowInsertingHyperlinks:=False, _
    AllowDeletingColumns:=True, _
    AllowDeletingRows:=True, _
    AllowSorting:=False, _
    AllowFiltering:=False, _
    AllowUsingPivotTables:=False

End Sub

Allow selection of any cells

Sub AllowSelectionAnyCells()

'Allowing selection of locked or unlocked cells
Sheets("Sheet1").EnableSelection = xlNoRestrictions

End Sub

Allow selection of unlocked cells

Sub AllowSelectionUnlockedCells()

'Allowing selection of unlocked cells only
Sheets("Sheet1").EnableSelection = xlUnlockedCells

End Sub

Don’t allow selection of any cells

Sub NoSelectionAllowed()

'Do not allow selection of any cells
Sheets("Sheet1").EnableSelection = xlNoSelection

End Sub

Allowing VBA code to make changes, even when protected

Even when protected, we still want our macros to make changes to the sheet. The following VBA code changes the setting to allow macros to make changes to a protected sheet.

Sub AllowVBAChangesOnProtectedSheet()

'Enable changes to worksheet by VBA code, even if protected
Sheets("Sheet1").Protect Password:="myPassword", _
    UserInterfaceOnly:=True

End Sub

Unfortunately, this setting is not saved within the workbook. It needs to be run every time the workbook opens. Therefore, calling the code in the Workbook_Open event of the Workbook module is probably the best option.

Allowing the use of the Group and Ungroup feature

To enable users to make use of the Group and Ungroup feature of protected sheets, we need to allow changes to the user interface and enable outlining.

Sub AllowGroupingAndUngroupOnProtectedSheet()

'Allow user to group and ungroup whilst protected
Sheets("Sheet1").Protect Password:="myPassword", _
    UserInterfaceOnly:=True

Sheets("Sheets1").EnableOutlining = True

End Sub

As noted above the UserInterfaceOnly setting is not stored in the workbook; therefore, it needs to be run every time the workbook opens.

Conclusion

Wow! That was a lot of code examples; hopefully, this covers everything you would ever need for using VBA to protect and unprotect sheets.

Related posts:

  • Office Scripts – Workbook & worksheet protection
  • VBA Code to Password Protect an Excel file
  • VBA code to Protect and Unprotect Workbooks

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

  • #2

That’s because you are protecting the sheet within the If statement itself. ActiveSheet.Protect = True does just that—protects the sheet.

You want ProtectContents:

Code:

If ActiveSheet.ProtectContents = True Then
    MsgBox "Is protected"
Else
    MsgBox "Not protected"
End If

  • #3

What I really want to do is:

If ActiveSheet.Protect=true Then ActiveSheet.Protect userinterfaceonly:=True

If the sheet is protected (no password) then let macros run on the sheet.
If the sheet is unprotected then don’t protect it.

  • #4

So, just change the If statement (untested):

Code:

If ActiveSheet.ProtectContents = True Then ActiveSheet.Protect UserInterfaceOnly:=True

  • #5

Thank you Pookie. It works. I hadn’t seen your reply when I composed my second post.

Detect Sheet Protection

Whenever working with a worksheet ever wondered why some menu buttons are not working or ribbon icons are greyed out and no functionality doesn’t work, this happened to me and because of a silly mistake.

I can’t say how many times this has happened to me while working on a spreadsheet and no realizing that it was being protected. I was working on a spreadsheet and realized I cannot copy data from the sheet, and why so? Because my spreadsheet was being protected.

Let’s see how we can figure out some of the ways we can check if the sheets are protected in the workbook and to get a list of all the sheets being protected.

Check the Ribbon

  1. If something doesn’t feel right with the sheet and you are not able to make any edits in the sheet check if the sheet is being protected or not if the sheet is being protected, you can move to the REVIEW TAB on the excel ribbon and check out the PROTECT BUTTON, If it says UNPROTECT SHEET, well you guessed it right, your sheet is being protected.
  2. Another way is to check if you have access to the ribbon buttons and all the buttons are not greyed out if all of the buttons are greyed out/ disabled meaning the sheet you are working on is being protected. The Home tab buttons are disabled.
  3. Another way is when you right-click on the sheet the menu that pops-up has disabled buttons, this means that sheet protection is being used on this sheet and you need to turn it off in order to work with this sheet.

VBA Function to check if the sheet is protected

This VBA code below checks if the Active Sheet is protected or not and returns are True value if protected and False if not protected, a very handy way and easy to check way, to check if the sheet is protected.

'check if the sheet has protection on
Function protected(sheet As Worksheet) As Boolean
protected = sheet.ProtectContents
End Function

Or we can write some VBA macro which can even check and return the names of the sheets that are being protected in this Active workbook

'give a list of all protected sheets
Sub protectedSheets()
Dim sheet As Worksheet
Dim visible As String
Dim hidden As String
For Each sheet In ActiveWorkbook.Worksheets
If sheet.ProtectContents = True Then
If sheet.Visible = xlSheetVisible Then
visible = visible & vbNewLine & " - " & sheet.Name
Else
hidden = hidden & vbNewLine & " - " & sheet.Name
End If
End If
Next sheet
'results
If hidden = "" And visible = "" Then
MsgBox "No worksheets protected"
Else
MsgBox "Protected Worksheets: " & _
vbNewLine & vbNewLine & "Visble :" & visible & _
vbNewLine & vbNewLine & "Hidden :" & hidden, , "Summary"
End If
End Sub

After this macro is used on a workbook it will list all of the sheets that are protected and checks all the sheets either hidden or visible.

Hopes this helps you in not making silly mistakes and not waste your time, if you have questions or suggestions, please let us know, Happy to help. ThankYou

Понравилась статья? Поделить с друзьями:
  • Vba excel if row hidden
  • Vba excel if not isnumeric
  • Vba excel if not is nothing then
  • Vba excel if not exists
  • Vba excel if not exist