Skip to main content

How to lock or protect cells after data entry or input in Excel?

Supposing you have a worksheet and just a certain range of blank cells needs data entry, and after finishing inputting data, you need the cells to be locked automatically in order to prevent changes again. How can you do to achieve it? This article can help you.

Lock or protect cells after data entry or input with VBA code


Lock or protect cells after data entry or input with VBA code

For example, the certain range of blank cells is A1:F8. Please do as follows to lock these cells after data entry in Excel.

1. Please unlock this range first, select the cells and right-clicking, then choose Format Cells in the right-clicking menu, and in the Format Cells dialog box, unchecking the Locked box under the protection tab, and finally clicking the OK button. See screenshot:

2. Click Review > Protect Sheet. And specify a password to protect this worksheet.

3. Right click the sheet tab, select View Code from the right-clicking menu. Then copy and paste the below VBA code into the Code window. See screenshot:

VBA code: Lock or protect cells after data entry or input

Dim mRg As Range
Dim mStr As String

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Range("A1:F8"), Target) Is Nothing Then
    Set mRg = Target.Item(1)
    mStr = mRg.Value
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xRg As Range
    On Error Resume Next
    Set xRg = Intersect(Range("A1:F8"), Target)
    If xRg Is Nothing Then Exit Sub
    Target.Worksheet.Unprotect Password:="123"
    If xRg.Value <> mStr Then xRg.Locked = True
    Target.Worksheet.Protect Password:="123" 
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Range("A1:F8"), Target) Is Nothing Then
    Set mRg = Target.Item(1)
     mStr = mRg.Value
End If
End Sub

Note: In the code, “A1:F8” is the range you need to input data; and “123” is the password of this protected worksheet. Please change them as you need.

4. Press Alt + Q keys simultaneously to close the Microsoft Visual Basic for Applications window.

After finishing entering data to the cells of range A1:F8, they will be locked automatically. And you will get a prompt dialog box if you try to change any cell content of this range. See screenshot:


Related articles:

Best Office Productivity Tools

🤖 Kutools AI Aide: Revolutionize data analysis based on: Intelligent Execution   |  Generate Code  |  Create Custom Formulas  |  Analyze Data and Generate Charts  |  Invoke Kutools Functions
Popular Features: Find, Highlight or Identify Duplicates   |  Delete Blank Rows   |  Combine Columns or Cells without Losing Data   |   Round without Formula ...
Super Lookup: Multiple Criteria VLookup    Multiple Value VLookup  |   VLookup Across Multiple Sheets   |   Fuzzy Lookup ....
Advanced Drop-down List: Quickly Create Drop Down List   |  Dependent Drop Down List   |  Multi-select Drop Down List ....
Column Manager: Add a Specific Number of Columns  |  Move Columns  |  Toggle Visibility Status of Hidden Columns  |  Compare Ranges & Columns ...
Featured Features: Grid Focus   |  Design View   |   Big Formula Bar    Workbook & Sheet Manager   |  Resource Library (Auto Text)   |  Date Picker   |  Combine Worksheets   |  Encrypt/Decrypt Cells    Send Emails by List   |  Super Filter   |   Special Filter (filter bold/italic/strikethrough...) ...
Top 15 Toolsets12 Text Tools (Add Text, Remove Characters, ...)   |   50+ Chart Types (Gantt Chart, ...)   |   40+ Practical Formulas (Calculate age based on birthday, ...)   |   19 Insertion Tools (Insert QR Code, Insert Picture from Path, ...)   |   12 Conversion Tools (Numbers to Words, Currency Conversion, ...)   |   7 Merge & Split Tools (Advanced Combine Rows, Split Cells, ...)   |   ... and more

Supercharge Your Excel Skills with Kutools for Excel, and Experience Efficiency Like Never Before. Kutools for Excel Offers Over 300 Advanced Features to Boost Productivity and Save Time.  Click Here to Get The Feature You Need The Most...

Description


Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!
Comments (75)
Rated 5 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
Good day, what I want to do is quite similar to the presented code however, the code only caters for individual data entry. My case is that I have a data entry interface but the given code doesn't follow the formulas before the selected cells which is substantial in my situation. Please, help me to resolve this. Thank you so much :D
This comment was minimized by the moderator on the site
I want to lock a particular range after an entry and allow only one entry in that range.
the range already contains a data validation.
This comment was minimized by the moderator on the site
Hi Rakesh Chand,
Assuming the specific range is A1:D7, when you select an entry in any data validation of that range, the worksheet will be protected.
Please apply the following VBA code to get it done.

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20220831
    Dim xRg As Range
    Dim Rg As Range
    On Error Resume Next
    Set Rg = Range("A1:D7")
    Set xRg = Intersect(Rg, Target)
    If xRg Is Nothing Then Exit Sub
       
    Rg.Locked = True
    
        Rg.Worksheet.Protect Password:="123"
    
End Sub
This comment was minimized by the moderator on the site
доброго времени суток!
Возможно ли с помощью кода сделать следующие?
Есть таблица, к примеру 6 столбцов, в которую последовательно вносят данные в 5 столбов (присутствует режим "выбор из списка данных" и формулы), а в 6-ом выбирается фамилия вносившего. Возможно ли блокировать полностью строку с внесенными данными, только после заполнения последней ячейке в этой строке (6-ой столбец)?
Выше указанный способ блокирует ввод данных в ячейки где есть выбор из списка данных на всём листе.
Если есть такой вариант, буду очень признателен за код.
Заранее Спасибо!
Rated 5 out of 5
This comment was minimized by the moderator on the site
Hi I am having an error with the deletion. Whenever I tried to click the delete the record a pop up will say "Microsoft Excel will permanently delete this sheet. Do you want to continue'.

Here's the code that I am using:

Sub Deletion()

Dim iRow As Long
Dim iSerial As Long


iSerial = Application.InputBox("Please enter Serial No. to delete the record.", "Delete", , , , , , 1)

On Error Resume Next

iRow = Application.WorksheetFunction.IfError _
(Application.WorksheetFunction.Match(iSerial, Sheets("Database").Range("A:A"), 0), 0)

On Error GoTo 0

If iRow = 0 Then

MsgBox "No record found.", vbOKOnly + vbCritical, "No Record"
Exit Sub

End If

Sheets("Database").Cells(iRow, 1).EntireRow.Delete Shift:=xlUp

End Sub


Please help me fix it. Thanks!
This comment was minimized by the moderator on the site
Hi guys. I need help and I'm new with VBA.
Say, I have Column BH with dropdown choices for Confirmed, Pending, and Cancelled.
All columns must remain unlocked for editing except for Columns A, BD, BE, and BF which must remain lock all the time.
If "Confirmed" is selected on Column BH, I want to lock the entire row before/next to it. Then, a password must be used if I want to edit the "Confirmed" row.
Can someone help me with this please?
Thanks in advance.

This comment was minimized by the moderator on the site
Good day...
Your tutorial is great!
I ran across a Run-Time error '13': during selection change if I select entire row. What is the turn-around for this? Any insight is much appreciated.
This comment was minimized by the moderator on the site
Hi,Which Excel version are you using?
This comment was minimized by the moderator on the site
Hi, This is all new to me. The formula is great. I want to lock cells D6:D36, H6:H35 & L6:L35 but can't get this to work. any help would be greatly appreciated.
This comment was minimized by the moderator on the site
Hi simon,If you want to lock cells in D6:D36, H6:H35 and L6:L35 separately after finish entering data in each range. Please do as follows.1. Select these three ranges by holding the Ctrl key;2. Do as the post described in step 1 to unlock these three ranges;3. Protect your worksheet with a password (Here my password is 123. This password will be used in the below code);4. Right click the sheet tab and then paste the below VBA code into the Code editor, and then press Alt + Q keys to close the Microsoft Visual Basic for Applications window.Notes: 1) In the code, you can change the ranges and password as you need;2)After pressing Alt + Q keys to close the code window, you need to shift to another worksheet and then go back to current sheet to make the code work. Otherwise, error will be occurred.<div data-tag="code">Dim mRg As Range
'Updated by Extendoffice 20201030
Dim mStr As String
Dim mStrAddress As String
Dim mArr
Private Sub Worksheet_Activate()
On Error Resume Next
Erase mArr()
mStrAddress = "D6:D36,H6:H35,L6:L35"
mArr = Split(mStrAddress, ",")
End Sub

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim xI As Integer
For xI = 0 To UBound(mArr)
If Not Intersect(Range(mArr(xI)), Target) Is Nothing Then
Set mRg = Target.Item(1)
mStr = mRg.Value
Exit For
End If
Next
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim xRg As Range
Dim xI As Integer
On Error Resume Next
For xI = 0 To UBound(mArr)
Set xRg = Null
Set xRg = Intersect(Range(mArr(xI)), Target)
If Not (xRg Is Nothing) Then
Target.Worksheet.Unprotect Password:="123"
If xRg.Value <> mStr Then xRg.Locked = True
Target.Worksheet.Protect Password:="123"

End If
Next
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim xI As Integer
On Error Resume Next
For xI = 0 To UBound(mArr)
If Not Intersect(Range(mArr(xI)), Target) Is Nothing Then
Set mRg = Target.Item(1)
mStr = mRg.Value
End If
Next
End Sub
This comment was minimized by the moderator on the site
If Not Intersect(Range("CUSTOMER!"), Target) Is Nothing Then
I got an error. I want to protect the whole sheet
This comment was minimized by the moderator on the site
Good afternoon ... thank you again for this great resource. I do have one question. We have a shared document that is used by multiple users for input purposes. We have noticed that if User A enters data in a given cell, User A cannot edit per the code above (which is exactly what we want) but User B who the document is also shared with can delete the data that User A entered. Is there a revision for the code above that could be included in a shared document that has multiple users that are entering data.
This comment was minimized by the moderator on the site
Hi
I want to auto lock cell while i'm saving my worksheet
Can you help me how to do this in vba
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations