You have a sheet with list of Tata cars.

The need is to sort them in ascending order of Model name upon clicking a button.

Data of Cars

Data of Cars

The VBA code to sort would be: –

Sub Button1_Click()

Range(“A:C”).Sort , Key1:=Range(“a1”), Order1:=xlAscending, Header:=True

End Sub

 

When you run this code, it will work perfectly and sort the data.

But if this sheet is protected, then you will get an error like this,

Error

Error

To make it work, you will need to

  1. Give the password alongwith before your code so that the Sheet is first Unprotected with .Unprotect
  2. The Sort code as mentioned earlier
  3. Then .Protect  to protect the Sheet again.

Let’s say the Sheet’s password is abc

 

Correct VBA Code: –

Sub Button1_Click()

Sheets(“Sheet1″).Unprotect Password:=”abc”

Range(“A:C”).Sort , Key1:=Range(“a1”), Order1:=xlAscending, Header:=True

Sheets(“Sheet1″).Protect Password:=”abc”

End Sub

Data Sorted

Data Sorted