User Interface Protection
VBA

Protect Excel Worksheet as UserInterFaceOnly

Just assume you a worksheet wherein you have few groups for column or rows and then you protected that worksheet. Now will you be able to expand or collapse those groups? No, you cannot expand or collapse it because it will show error as worksheet is protected.

How to expand or collapse group while worksheet is protected
How to expand or collapse group while worksheet is protected

 

If your worksheet is protected and you want to enter some value on protected cells using VBA, then it shows some runtime error because you cannot enter the value on protected worksheet even using VBA.

In this case you need to protect your worksheet as UserInterFaceOnly using VBA.

What is UserInterFaceOnly?

The UserInterFaceOnly  is an optional argument of the ProtectMethod in VBA that we can set to True. By default, it is False. By setting this argument to True Excel will allow all Excel VBA macros to run on the Worksheet that protected with or without a password. For manual changes it will be still protected.

Below is the example of code wherein we are entering the data on protected worksheet using VBA.

Sub Protect_Sheet()

    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Sheet1")

    sh.Protect "1234", userinterfaceonly:=True
    sh.Range("E4").Value = "WWW.PK-AnExcelExpert.Com"

End Sub

If you save, then reopen the workbook that contains this wonderful piece of code, this worksheet will remain protected and your macro can’t enter the value. The code must run each time you open the workbook. So, the better option is put your code on workbook open event.

Now for the first scenario expand and collapse group on protected worksheet, just put below code on workbook open event

Private Sub Workbook_Open()

Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Employee Sales")

sh.Protect "1234", userinterfaceonly:=True
sh.EnableOutlining = True

End Sub

 

Click here to download this practice file.

 

Watch the step by step video tutorial:

PK
My Name is PK. I am founder of PK-AnExcelExpert.com. I am a Microsoft Certified Professional. I have more than 10 years of experience in Data Visualization, Excel Automation and dashboard creation. Excel is my passion and I like to do always something innovative in Excel and share it with other people.
https://www.pk-anexcelexpert.com