I have an Excel worksheet that acts like an application, with form control buttons allowing users to ‘navigate’ through records. First, Previous, Next & Last cycle appropriately through one of the worksheets records, displaying the values in my ‘form’ worksheet.
When users are not in Edit or Add Mode, I would like to lock the cells to prevent users from modifying contents.
I tried Range(«A1:O24»).Locked = True, but I am still able to type new values into the cells.
Anyone know how to accomplish this? I need my vba code to be able to assign new values to the cells as users ‘navigate’, but to prevent users from entering new values unless in Add or Edit mode.
asked Jun 14, 2013 at 15:09
Analytic LunaticAnalytic Lunatic
3,84522 gold badges76 silver badges119 bronze badges
2
I believe the reason for this is that you need to protect a worksheet before cells actually become locked. All cells are formatted as locked as a default so what you really want to do is set the range that you don’t want locked to Range().Locked = False and then set the worksheet to protected.
In the case that you want all cells locked all you have to do is set the worksheet to protected
answered Jun 14, 2013 at 15:13
1
Search for your condition whether user was not in Edit or Add mode and then locking your range and finally protect your worksheet.
Let’s say for example in one case, if you want to locked cells from range A1 to I50 then below is the code:
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"
In another case if you already have a protected sheet then follow below code:
ActiveSheet.Unprotect Password:="Enter your Password"
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"
answered Sep 18, 2013 at 9:34
Milan ShethMilan Sheth
84412 silver badges10 bronze badges
Users entering data into the wrong cells or changing existing formulas can make data collection a tedious process. However, you can prevent users from going outside the intended boundaries by disabling certain sections of your workbook. In this article, we’re going to show you how to lock a cell in Excel formula using VBA.
Protection
Worksheets are objects in a workbook’s worksheet collection and they have Protect and Unprotect methods. These methods determine the protected status of a worksheet as the name suggests. Both methods can get accept other optional arguments. The first is the password argument. By setting a string for the parameter argument, you can lock your worksheets with a password. Below is a breakdown.
Lock Cells
Important note: Protecting a sheet does not lock individual cells! The cells you want to lock should be marked as Locked too. A cell can be marked as Locked, and/or Hidden, in two ways:
- Via user interface
- Via VBA
The User Interface method requires using the Format Cells dialog. Select a cell or a range of cells, and press Ctrl + 1 to open this menu and go to the Protection tab. Use the corresponding checkboxes to activate properties.
The second method is doing this via VBA code. Every cell and range can be made Locked and FormulaHidden properties. Set these two as True or False to change their status.
Activecell.Locked = True Activecell.FormulaHidden = True
You can use the Hidden status to hide your formulas as well.
Detect Cells with Formulas
If you just need to lock only cells with formulas, you need to first identify cells that have formulas. The cells and ranges have a HasFormula property, which makes them read only. It returns a Boolean value based on whether the cell or range has a formula. A simple loop can be used to detect cells in a given range that contain formula.
For Each rng In ActiveSheet.Range("B4:C9") If rng.HasFormula Then rng.Locked = True Else rng.Locked = False End If Next rng
To run this code, you need to add a module into the workbook or the add-in file. Copy and paste the code into the module to run it. The main advantage of the module method is that it allows saving the code in the file, so that it can be used again later. Furthermore, the subroutines in modules can be used by icons in the menu ribbons or keyboard shortcuts. Remember to save your file in either XLSM or XLAM format to save your VBA code.
Lock cells and protect a worksheet
The code example below checks every cell in the range «B4:C9» from the active worksheet. If a cell has a formula, it locks the cell. Otherwise, the cell becomes or remains unlocked.
Sub ProtectCellsWithFormulas() For Each rng In ActiveSheet.Range("B4:C9") If rng.HasFormula Then rng.Locked = True Else rng.Locked = False End If Next rng ActiveSheet.Protect "pass" End Sub
Protecting and unprotecting sheets is a common action for an Excel user. There is nothing worse than when somebody, who doesn’t know what they’re doing, overtypes essential formulas and cell values. It’s even worse when that person happens to be us; all it takes is one accidental keypress, and suddenly the entire worksheet is filled with errors. In this post, we explore using VBA to protect and unprotect sheets.
Protection is not foolproof but prevents accidental alteration by an unknowing user.
Sheet protection is particularly frustrating as it has to be applied one sheet at a time. If we only need to protect a single sheet, that’s fine. But if we have more than 5 sheets, it is going to take a while. This is why so many people turn to a VBA solution.
The VBA Code Snippets below show how to do most activities related to protecting and unprotecting sheets.
Download the example file: Click the link below to download the example file used for this post:
Adapting the code for your purposes
Unless stated otherwise, every example below is based on one specific worksheet. Each code includes Sheets(“Sheet1”)., this means the action will be applied to that specific sheet. For example, the following protects Sheet1.
Sheets("Sheet1").Protect
But there are lots of ways to reference sheets for protecting or unprotecting. Therefore we can change the syntax to use one of the methods shown below.
Using the active sheet
The active sheet is whichever sheet is currently being used within the Excel window.
ActiveSheet.Protect
Applying a sheet to a variable
If we want to apply protection to a sheet stored as a variable, we could use the following.
Dim ws As Worksheet
Set ws = Sheets("Sheet1")
ws.Protect
Later in the post, we look at code examples to loop through each sheet and apply protection quickly.
Let’s begin with some simple examples to protect and unprotect sheets in Excel.
Protect a sheet without a password
Sub ProtectSheet()
'Protect a worksheet
Sheets("Sheet1").Protect
End Sub
Unprotect a sheet (no password)
Sub UnProtectSheet()
'Unprotect a worksheet
Sheets("Sheet1").Unprotect
End Sub
Protecting and unprotecting with a password
Adding a password to give an extra layer of protection is easy enough with VBA. The password in these examples is hardcoded into the macro; this may not be the best for your scenario. It may be better to apply using a string variable, or capturing user passwords with an InputBox.
VBA Protect sheet with password
Sub ProtectSheetWithPassword()
'Protect worksheet with a password
Sheets("Sheet1").Protect Password:="myPassword"
End Sub
VBA Unprotect sheet with a password
Sub UnProtectSheetWithPassword()
'Unprotect a worksheet with a password
Sheets("Sheet1").Unprotect Password:="myPassword"
End Sub
NOTE – It is not necessary to unprotect, then re-protect a sheet to change the settings. Instead, just protect again with the new settings.
Using a password based on user input
Using a password that is included in the code may partly defeat the benefit of having a password. Therefore, the codes in this section provide examples of using VBA to protect and unprotect based on user input. In both scenarios, clicking Cancel is equivalent to entering no password.
Protect with a user-input password
Sub ProtectSheetWithPasswordFromUser()
'Protect worksheet with a password
Sheets("Sheet1").Protect Password:=InputBox("Enter a protection password:")
End Sub
Unprotect with a user-input password
Sub UnProtectSheetWithPasswordFromUser()
'Protect worksheet with a password
Sheets("Sheet1").Unprotect _
Password:=InputBox("Enter a protection password:")
End Sub
Catching errors when incorrect password entered
If an incorrect password is provided, the following error message displays.
The code below catches the error and provides a custom message.
Sub CatchErrorForWrongPassword()
'Keep going even if error found
On Error Resume Next
'Apply the wrong password
Sheets("Sheet1").Unprotect Password:="incorrectPassword"
'Check if an error has occured
If Err.Number <> 0 Then
MsgBox "The Password Provided is incorrect"
Exit Sub
End If
'Reset to show normal error messages
On Error GoTo 0
End Sub
If you forget a password, don’t worry, the protection is easy to remove.
Applying protection to different parts of the worksheet
VBA provides the ability to protect 3 aspects of the worksheet:
- Contents – what you see on the grid
- Objects – the shapes and charts which are on the face of the grid
- Scenarios – the scenarios contained in the What If Analysis section of the Ribbon
By default, the standard protect feature will apply all three types of protection at the same time. However, we can be specific about which elements of the worksheet are protected.
Protect contents
Sub ProtectSheetContents()
'Apply worksheet contents protection only
Sheets("Sheet1").Protect Password:="myPassword", _
DrawingObjects:=False, _
Contents:=True, _
Scenarios:=False
End Sub
Protect objects
Sub ProtectSheetObjects()
'Apply worksheet objects protection only
Sheets("Sheet1").Protect Password:="myPassword", _
DrawingObjects:=True, _
Contents:=False, _
Scenarios:=False
End Sub
Protect scenarios
Sub ProtectSheetScenarios()
'Apply worksheet scenario protection only
Sheets("Sheet1").Protect Password:="myPassword", _
DrawingObjects:=False, _
Contents:=False, _
Scenarios:=True
End Sub
Protect contents, objects and scenarios
Sub ProtectSheetAll()
'Apply worksheet protection to contents, objects and scenarios
Sheets("Sheet1").Protect Password:="myPassword", _
DrawingObjects:=True, _
Contents:=True, _
Scenarios:=True
End Sub
Applying protection to multiple sheets
As we have seen, protection is applied one sheet at a time. Therefore, looping is an excellent way to apply settings to a lot of sheets quickly. The examples in this section don’t just apply to Sheet1, as the previous examples have, but include all worksheets or all selected worksheets.
Protect all worksheets in the active workbook
Sub ProtectAllWorksheets()
'Create a variable to hold worksheets
Dim ws As Worksheet
'Loop through each worksheet in the active workbook
For Each ws In ActiveWorkbook.Worksheets
'Protect each worksheet
ws.Protect Password:="myPassword"
Next ws
End Sub
Protect the selected sheets in the active workbook
Sub ProtectSelectedWorksheets()
Dim ws As Worksheet
Dim sheetArray As Variant
'Capture the selected sheets
Set sheetArray = ActiveWindow.SelectedSheets
'Loop through each worksheet in the active workbook
For Each ws In sheetArray
On Error Resume Next
'Select the worksheet
ws.Select
'Protect each worksheet
ws.Protect Password:="myPassword"
On Error GoTo 0
Next ws
sheetArray.Select
End Sub
Unprotect all sheets in active workbook
Sub UnprotectAllWorksheets()
'Create a variable to hold worksheets
Dim ws As Worksheet
'Loop through each worksheet in the active workbook
For Each ws In ActiveWorkbook.Worksheets
'Unprotect each worksheet
ws.Unprotect Password:="myPassword"
Next ws
End Sub
Checking if a worksheet is protected
The codes in this section check if each type of protection has been applied.
Check if Sheet contents is protected
Sub CheckIfSheetContentsProtected()
'Check if worksheets contents is protected
If Sheets("Sheet1").ProtectContents Then MsgBox "Protected Contents"
End Sub
Check if Sheet objects are protected
Sub CheckIfSheetObjectsProtected()
'Check if worksheet objects are protected
If Sheets("Sheet1").ProtectDrawingObjects Then MsgBox "Protected Objects"
End Sub
Check if Sheet scenarios are protected
Sub CheckIfSheetScenariosProtected()
'Check if worksheet scenarios are protected
If Sheets("Sheet1").ProtectScenarios Then MsgBox "Protected Scenarios"
End Sub
Changing the locked or unlocked status of cells, objects and scenarios
When a sheet is protected, unlocked items can still be edited. The following codes demonstrate how to lock and unlock ranges, cells, charts, shapes and scenarios.
When the sheet is unprotected, the lock setting has no impact. Each object becomes locked on protection.
All the examples in this section set each object/item to lock when protected. To set as unlocked, change the value to False.
Lock a cell
Sub LockACell()
'Changing the options to lock or unlock cells
Sheets("Sheet1").Range("A1").Locked = True
End Sub
Lock all cells
Sub LockAllCells()
'Changing the options to lock or unlock cells all cells
Sheets("Sheet1").Cells.Locked = True
End Sub
Lock a chart
Sub LockAChart()
'Changing the options to lock or unlock charts
Sheets("Sheet1").ChartObjects("Chart 1").Locked = True
End Sub
Lock a shape
Sub LockAShape()
'Changing the option to lock or unlock shapes
Sheets("Sheet1").Shapes("Rectangle 1").Locked = True
End Sub
Lock a Scenario
Sub LockAScenario()
'Changing the option to lock or unlock a scenario
Sheets("Sheet1").Scenarios("scenarioName").Locked = True
End Sub
Allowing actions to be performed even when protected
Even when protected, we can allow specific operations, such as inserting rows, formatting cells, sorting, etc. These are the same options as found when manually protecting the sheet.
Allow sheet actions when protected
Sub AllowSheetActionsWhenProtected()
'Allowing certain actions even if the worksheet is protected
Sheets("Sheet1").Protect Password:="myPassword", _
DrawingObjects:=False, _
Contents:=True, _
Scenarios:=False, _
AllowFormattingCells:=True, _
AllowFormattingColumns:=True, _
AllowFormattingRows:=True, _
AllowInsertingColumns:=False, _
AllowInsertingRows:=False, _
AllowInsertingHyperlinks:=False, _
AllowDeletingColumns:=True, _
AllowDeletingRows:=True, _
AllowSorting:=False, _
AllowFiltering:=False, _
AllowUsingPivotTables:=False
End Sub
Allow selection of any cells
Sub AllowSelectionAnyCells()
'Allowing selection of locked or unlocked cells
Sheets("Sheet1").EnableSelection = xlNoRestrictions
End Sub
Allow selection of unlocked cells
Sub AllowSelectionUnlockedCells()
'Allowing selection of unlocked cells only
Sheets("Sheet1").EnableSelection = xlUnlockedCells
End Sub
Don’t allow selection of any cells
Sub NoSelectionAllowed()
'Do not allow selection of any cells
Sheets("Sheet1").EnableSelection = xlNoSelection
End Sub
Allowing VBA code to make changes, even when protected
Even when protected, we still want our macros to make changes to the sheet. The following VBA code changes the setting to allow macros to make changes to a protected sheet.
Sub AllowVBAChangesOnProtectedSheet()
'Enable changes to worksheet by VBA code, even if protected
Sheets("Sheet1").Protect Password:="myPassword", _
UserInterfaceOnly:=True
End Sub
Unfortunately, this setting is not saved within the workbook. It needs to be run every time the workbook opens. Therefore, calling the code in the Workbook_Open event of the Workbook module is probably the best option.
Allowing the use of the Group and Ungroup feature
To enable users to make use of the Group and Ungroup feature of protected sheets, we need to allow changes to the user interface and enable outlining.
Sub AllowGroupingAndUngroupOnProtectedSheet()
'Allow user to group and ungroup whilst protected
Sheets("Sheet1").Protect Password:="myPassword", _
UserInterfaceOnly:=True
Sheets("Sheets1").EnableOutlining = True
End Sub
As noted above the UserInterfaceOnly setting is not stored in the workbook; therefore, it needs to be run every time the workbook opens.
Conclusion
Wow! That was a lot of code examples; hopefully, this covers everything you would ever need for using VBA to protect and unprotect sheets.
Related posts:
- Office Scripts – Workbook & worksheet protection
- VBA Code to Password Protect an Excel file
- VBA code to Protect and Unprotect Workbooks
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).
Do you need help adapting this post to your needs?
I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:
- Remove From My Forums
-
Question
-
Hi there
I am working on a excel sheet (excel 2010) what I wanted to do is once the user enter a value to the cell I wanted that cell to be lock with the value where no one can change the value.
So e.g cell A1 User enter value 100 once user move away from the cell the I want to lock the cell with the value in this case its A1
How can I do this ?
Answers
-
Select all cells (press Ctrl+A, if that selects the current range only, press Ctrl+A again).
Press Ctrl+1 to activate the Format Cells dialog, then activate the Protection tab. Clear the Locked check box, then click OK.
Activate the Review tab of the ribbon. Click Protect Sheet. Tick or clear check boxes to determine what users are allowed to do, and ifd desired specify a password. Click OK.
Right-click the sheet tab, and select View Code from the context menu. Enter the following code in the worksheet module:
Private Sub Worksheet_Change(ByVal Target As Range) Dim cel As Range ActiveSheet.Unprotect ' Password:="secret" For Each cel In Target If cel.Value <> "" Then cel.Locked = True End If Next cel ActiveSheet.Protect ' Password:="secret" End Sub
Save the workbook as a .xlsm, .xlsb or .xls workbook, not as a .xlsx workbook (those don’t support macros).
Regards, Hans Vogelaar
-
Marked as answer by
Wednesday, March 28, 2012 11:38 AM
-
Marked as answer by
Содержание
- How to lock a cell in Excel formula using VBA
- Protection
- Lock Cells
- Detect Cells with Formulas
- Lock cells and protect a worksheet
- How to unlock and lock Excel cells for running a macro
- 4 Answers 4
- How to Lock the data in a cell in excel using vba
- 5 Answers 5
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- How to lock specific cells but allow filtering and sorting
- 10 Answers 10
- Lock certain cells in a range
- 7 Answers 7
How to lock a cell in Excel formula using VBA
Users entering data into the wrong cells or changing existing formulas can make data collection a tedious process. However, you can prevent users from going outside the intended boundaries by disabling certain sections of your workbook. In this article, we’re going to show you how to lock a cell in Excel formula using VBA.
Protection
Worksheets are objects in a workbook’s worksheet collection and they have Protect and Unprotect methods. These methods determine the protected status of a worksheet as the name suggests. Both methods can get accept other optional arguments. The first is the password argument. By setting a string for the parameter argument, you can lock your worksheets with a password. Below is a breakdown.
Lock Cells
Important note: Protecting a sheet does not lock individual cells! The cells you want to lock should be marked as Locked too. A cell can be marked as Locked, and/or Hidden, in two ways:
The User Interface method requires using the Format Cells dialog. Select a cell or a range of cells, and press Ctrl + 1 to open this menu and go to the Protection tab. Use the corresponding checkboxes to activate properties.
The second method is doing this via VBA code. Every cell and range can be made Locked and FormulaHidden properties. Set these two as True or False to change their status.
You can use the Hidden status to hide your formulas as well.
Detect Cells with Formulas
If you just need to lock only cells with formulas, you need to first identify cells that have formulas. The cells and ranges have a HasFormula property, which makes them read only. It returns a Boolean value based on whether the cell or range has a formula. A simple loop can be used to detect cells in a given range that contain formula.
To run this code, you need to add a module into the workbook or the add-in file. Copy and paste the code into the module to run it. The main advantage of the module method is that it allows saving the code in the file, so that it can be used again later. Furthermore, the subroutines in modules can be used by icons in the menu ribbons or keyboard shortcuts. Remember to save your file in either XLSM or XLAM format to save your VBA code.
Lock cells and protect a worksheet
The code example below checks every cell in the range «B4:C9» from the active worksheet. If a cell has a formula, it locks the cell. Otherwise, the cell becomes or remains unlocked.
Источник
How to unlock and lock Excel cells for running a macro
I have a spreadsheet that has two buttons — To retrieve records from database and another one to upload changes from excel to database. The macro for retrieving records from Database is as follows. Now after retrieving the records, I want the users only to edit certain columns( here the columns from January to Scenario) so that the users, after updating those cells can click on the update button to save the changes to the database. However, I don’t want them to touch the other columns ( EmpID through Status).I want a macro that would lock those columns after data retrieval and unlock while retrieving the records on clicking the Retrieval button. This is because I am clearing the worksheet whenever I click on the retrieve records buttons. I tried several methods and it’s not working. I would appreciate your help.
4 Answers 4
One of the best ways to learn how to do something in VBA is simply to perform the task with the Macro Recorder on. That way you will know the basic code required to complete the task.
It also helps to understand that all cells start off with a property of «Locked» but that only becomes useful when the workbook is Protected using the Review > Protect Sheet option.
So to make sure no one can change all any of the cells in your book after the data has been changed, you’d need to protect the workbook using:
The various options could be changed or removed depending on what you want done.
As I understand it, you want only certain columns locked. In this case, you actually have to unlock the cells you will allow them to enter — so you have to think about it backwards.
This line of code would set the Locked property of the cells C1:C1000 to False so that when the Workbook is Protected, the user can still edit the cells:
If you have any other questions, just post.
Источник
How to Lock the data in a cell in excel using vba
I want to stop others from editing the cell contents in my excel sheet using VBA. Is it possible to do this?
5 Answers 5
You can first choose which cells you don’t want to be protected (to be user-editable) by setting the Locked status of them to False:
Then, you can protect the sheet, and all the other cells will be protected. The code to do this, and still allow your VBA code to modify the cells is:
Try using the Worksheet.Protect method, like so:
You should, however, be concerned about including the password in your VBA code. You don’t necessarily need a password if you’re only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.
Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That’s a good way to get started in VBA.
Let’s say for example in one case, if you want to locked cells from range A1 to I50 then below is the code:
In another case if you already have a protected sheet then follow below code:
You can also do it on the worksheet level captured in the worksheet’s change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect.
Linked
Hot Network Questions
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43331
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
How to lock specific cells but allow filtering and sorting
I’m using the following code to lock the content of certain cells
It locks the content of those specific columns. The problem is users cannot sort, neither filter, nor apply borders to the cells since those Excel menu items are disabled.
I thought the AllowSorting:=True , AllowFiltering:=True and DrawingObjects:=True would allow that the same way the AllowFormattingColumns:=True and AllowFormattingRows:=True allowed resizing.
10 Answers 10
There are a number of people with this difficulty. The prevailing answer is that you can’t protect content from editing while allowing unhindered sorting. Your options are:
1) Allow editing and sorting 🙁
2) Apply protection and create buttons with code to sort using VBA. There are other posts explaining how to do this. I think there are two methods, either (1) get the code to unprotect the sheet, apply the sort, then re-protect the sheet, or (2) have the sheet protected using UserInterfaceOnly:=True .
3) Lorie’s answer which does not allow users to select cells (https://stackoverflow.com/a/15390698/269953)
4) One solution that I haven’t seen discussed is using VBA to provide some basic protection. For example, detect and revert changes using Worksheet_Change . It’s far from an ideal solution however.
5) You could keep the sheet protected when the user is selecting the data and unprotected when the user has the header is selected. This leaves countless ways the users could mess up the data while also causing some usability issues, but at least reduces the odds of pesky co-workers thoughtlessly making unwanted changes.
Источник
Lock certain cells in a range
I’m trying to loop through a range of cells, locking any cell that has content while leaving empty cells unlocked.
When I run the below code the result is the entire sheet is locked. If I add an else statement the sheet is unlocked. Basically whatever the last .locked = (true, false) statement is is how the entire sheet winds up.
Change 1 Is it possible that I have some setting on/off that is interfering since I’m the only one who is unable to get any of this to work?
7 Answers 7
You can try this.
If you say Range(«A1»).Select, then it locks only A1. You can specify multiple cells to be locked by specifying as follows:
A3:A12,D3:E12,J1:R13,W18
This locks A3 to A12 and D3 to E12 etc.
I may be missing something but.
. will lock all cells on the active sheet. If you just change it to.
. then it works; I think?! As the range is very small, you may as well not unlock cells at the start, and instead unlock cells whilst locking them e.g.
If you are new to VBA, I would recommend cycling through code line-by-line as described in this Excel consultant’s video. If you step through code, you can check «has cell A7 behaved as expected?». instead of just seeing the end product
A quick way to unlock non-blank cells is to use SpecialCells see below.
On my testing this code handles merged cells ok, I think this is what is generating your error on Tim’s code when it looks to handle each cell individually (which to be clear is not an issue in Tim’s code, it is dealing with an unexpected outcome)
You may also find this article of mine A fast method for determining the unlocked cell range useful
I know this is an old thread, but I’ve been stuck on this for a while too, and after some testing on Excel 2013 here’s what I conclude if your range includes any merged cell
- The merged cells must be entirely included within that range (e.g. the merging must be entirely within the range being lock/unlocked
- The range being merged can be larger, or at least exactly the range corresponding to the merged cells. If it’s a named range that works as well.
Also, you cannot lock/unlock a cell that is already within a protected range. E.g if you run:
Twice it will work the first time, and fail the second time around. So you should unprotect the target range (or the sheet) before.
Источник