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.
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,
To make it work, you will need to
- Give the password alongwith before your code so that the Sheet is first Unprotected with .Unprotect
- The Sort code as mentioned earlier
- 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