Conditional Lock Cell , unable to sort

I am trying to write a macro that will lock any cell greater than 0. When I run the code below it works but locks the 1st row where I have a drop down arrow that does sorting and number filters. Is there a way to add to this code so that the first row wont be locked?

Sub Test()
    Dim Cell As Range
    Dim MyPlage As Range

    With ThisWorkbook.ActiveSheet
        .Cells.Locked = False
        Set MyPlage = .Range("J2:AA1074")
        For Each Cell In MyPlage
            If Not IsError(Cell) Then
                If Cell.Value > "0" Then
                    Cell.Locked = True
                End If
            End If
    End With

End Sub


You can add following code to the Sheet module (change Range("J1:AA1") to the range with your autofilter):

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Application.Intersect(Target, Range("J1:AA1")) Is Nothing Then
    End If
End Sub

The most simplest was is to define your range which doesn't include the Top Row :)





Also, Instead of looping through every cell in the range and checking if that cell has an error or not, you can directly use SpecialCells. For example (TRIED AND TESTED)

Sub Sample()
    Dim Cell As Range, MyPlage As Range, FinalRange As Range

    With ThisWorkbook.ActiveSheet
        .Cells.Locked = False

        On Error Resume Next
        Set MyPlage = .Range("J3:AA1074").SpecialCells(xlCellTypeConstants)
        On Error GoTo 0

        If Not MyPlage Is Nothing Then
            For Each Cell In MyPlage
                If Cell.Value > 0 Then Cell.Locked = True
        End If

        .Protect DrawingObjects:=True, _
                 Contents:=True, _
                 Scenarios:=True, _
                 AllowFiltering:=True, _

        .EnableSelection = xlUnlockedCells
    End With
End Sub

To ensure that Autofilter and Sorting works, specify it in .Protect as I have done above.

Before you run the above code, you also need to take one extra step.

  1. Unprotect the worksheet if it is already protected
  2. Under Review Tab, click on "Allow Users to Edit Ranges"
  3. Add "New" range
  4. Select the range you want allow users to sort


Need Your Help

Operation is not allowed - Picklist value Salesforce API

salesforce jitterbit

I have a simple upsert operation using the Jitterbit data loader. I am trying to create a new case record in Salesforce. One of the attributes of the case object is the case origin. This is a pickl...

When I try to get a background on my website with css/html it wont show the background

html css background

I'm trying to get a background on my website, and i have this