Salt la conținutul principal

Cum se blochează sau se protejează celulele după introducerea sau introducerea datelor în Excel?

Presupunând că aveți o foaie de lucru și doar o anumită gamă de celule goale necesită introducerea datelor, iar după ce ați terminat introducerea datelor, aveți nevoie ca celulele să fie blocate automat pentru a preveni din nou modificările. Cum poți face pentru a o realiza? Acest articol vă poate ajuta.

Blocați sau protejați celulele după introducerea sau introducerea datelor cu cod VBA


Blocați sau protejați celulele după introducerea sau introducerea datelor cu cod VBA

De exemplu, o anumită gamă de celule goale este A1: F8. Vă rugăm să faceți următoarele pentru a bloca aceste celule după introducerea datelor în Excel.

1. Deblocați mai întâi acest interval, selectați celulele și faceți clic dreapta, apoi alegeți Celule de format în meniul cu clic dreapta și în Celule de format casetă de dialog, debifând fișierul blocat caseta de sub protecţie , apoi faceți clic pe OK buton. Vedeți captura de ecran:

2. clic Recenzie > Protejați foaia. Și specificați o parolă pentru a proteja această foaie de lucru.

3. Faceți clic dreapta pe fila foi, selectați Afișați codul din meniul cu clic dreapta. Apoi copiați și lipiți codul VBA de mai jos în fereastra Cod. Vedeți captura de ecran:

Cod VBA: Blocați sau protejați celulele după introducerea sau introducerea datelor

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

notițe: În cod, „A1: F8” este intervalul de care aveți nevoie pentru a introduce date; iar „123” este parola acestei foi de lucru protejate. Vă rugăm să le schimbați după cum aveți nevoie.

4. presa Alt + Q tastele simultan pentru a închide Microsoft Visual Basic pentru aplicații fereastră.

După terminarea introducerii datelor în celulele din intervalul A1: F8, acestea vor fi blocate automat. Și veți primi o casetă de dialog promptă dacă încercați să modificați orice conținut de celulă din acest interval. Vedeți captura de ecran:


Articole pe aceeași temă:

Cele mai bune instrumente de productivitate de birou

🤖 Kutools AI Aide: Revoluționați analiza datelor pe baza: Execuție inteligentă   |  Generați codul  |  Creați formule personalizate  |  Analizați datele și generați diagrame  |  Invocați funcțiile Kutools...
Caracteristici populare: Găsiți, evidențiați sau identificați duplicatele   |  Ștergeți rândurile goale   |  Combinați coloane sau celule fără a pierde date   |   Rundă fără Formula ...
Super căutare: VLookup cu mai multe criterii    VLookup cu valori multiple  |   VLookup pe mai multe foi   |   Căutare fuzzy ....
Listă derulantă avansată: Creați rapid o listă derulantă   |  Listă drop-down dependentă   |  Listă derulantă cu selectare multiplă ....
Manager de coloane: Adăugați un număr specific de coloane  |  Mutați coloanele  |  Comutați starea vizibilității coloanelor ascunse  |  Comparați intervale și coloane ...
Caracteristici prezentate: Focus pe grilă   |  Vedere de proiectare   |   Big Formula Bar    Manager registru de lucru și foi   |  Biblioteca de resurse (Text automat)   |  Data Picker   |  Combinați foi de lucru   |  Criptare/Decriptare celule    Trimiteți e-mailuri după listă   |  Super Filtru   |   Filtru special (filtrează bold/italic/barat...) ...
Top 15 seturi de instrumente12 Text Instrumente (Adăuga text, Eliminați caractere,...)   |   50+ Diagramă Tipuri de (Gantt Chart,...)   |   40+ Practic Formule (Calculați vârsta pe baza zilei de naștere,...)   |   19 inserare Instrumente (Introduceți codul QR, Inserați imaginea din cale,...)   |   12 Convertire Instrumente (Numere la cuvinte, conversie valutara,...)   |   7 Merge & Split Instrumente (Rânduri combinate avansate, Celule divizate,...)   |   ... și altele

Îmbunătățiți-vă abilitățile Excel cu Kutools pentru Excel și experimentați eficiența ca niciodată. Kutools pentru Excel oferă peste 300 de funcții avansate pentru a crește productivitatea și a economisi timp.  Faceți clic aici pentru a obține funcția de care aveți cea mai mare nevoie...

Descriere


Fila Office aduce interfața cu file în Office și vă face munca mult mai ușoară

  • Activați editarea și citirea cu file în Word, Excel, PowerPoint, Publisher, Access, Visio și Project.
  • Deschideți și creați mai multe documente în filele noi ale aceleiași ferestre, mai degrabă decât în ​​ferestrele noi.
  • Vă crește productivitatea cu 50% și reduce sute de clicuri de mouse pentru dvs. în fiecare zi!
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