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.
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.