Protect worksheet without stopping a macro from running?

wrecclesham

New Member
Joined
Jul 24, 2019
Messages
45
I have a worksheet that I wish to enable protection on.

Unfortunately, whenever the worksheet is in a protected state and I update any values in any unlocked cells which the macro automatically applies sorting to, the following error appears:



Even if no cells have a "locked" attribute when I protect my worksheet, I still get this error whenever my macro attempts to automatically sort any dates entered, so it seems that enabling protection simply blocks some macro code from running, regardless of which cells are actually locked.

I've done some research and it seems that I need to use the following code in order to only lock the user interface, without preventing macros from running:

Code:
Me.Protect UserInterfaceOnly := True
Can someone please show me how I should add it to my existing code?

I have tried inserting the following before my existing code but it made no difference:

Code:
Public Sub AllowMacros()

Me.Protect UserInterfaceOnly:=True

End Sub
Here is my existing code:

Code:
Private Sub Worksheet_Change(ByVal Target As Range)

Application.EnableEvents = False
 With Range("A1:A11")
      .Offset(, 4).Formula = "=IF(ISTEXT(D1),1,if(d1="""",9999999,D1))"
      .Resize(, 5).Sort key1:=Range("e1"), order1:=xlAscending, Header:=xlYes
      .Offset(, 4).Clear
   End With
Application.EnableEvents = True
    Range("A13:D18").Sort key1:=Range("D1"), _
      order1:=xlAscending, Header:=xlYes, _
      OrderCustom:=1, MatchCase:=False, _
      Orientation:=xlTopToBottom
    
    Range("A20:C30").Sort key1:=Range("A1"), _
      order1:=xlAscending, Header:=xlYes, _
      OrderCustom:=1, MatchCase:=False, _
      Orientation:=xlTopToBottom
    
End Sub
 
Last edited:

pwill

Active Member
Joined
Nov 22, 2015
Messages
404
If you right click the worksheet and choose protect sheet, in the dialog box that pops up, there's an option to Allow Sort. That might help?
 

Forum statistics

Threads
1,077,851
Messages
5,336,762
Members
399,102
Latest member
chudson1

Some videos you may like

This Week's Hot Topics

Top