Přejít k hlavnímu obsahu

Jak zamknout nebo chránit buňky po zadání dat nebo vstupu v aplikaci Excel?

Předpokládejme, že máte list a jen určitý rozsah prázdných buněk vyžaduje zadávání dat, a po dokončení zadávání dat je třeba buňky automaticky uzamknout, aby se zabránilo dalším změnám. Jak můžete toho dosáhnout? Tento článek vám může pomoci.

Zamkněte nebo ochraňte buňky po zadání nebo vstupu dat pomocí kódu VBA


Zamkněte nebo ochraňte buňky po zadání nebo vstupu dat pomocí kódu VBA

Například určitý rozsah prázdných buněk je A1: F8. Po uzamčení těchto buněk po zadání dat v aplikaci Excel postupujte takto.

1. Nejprve prosím odemkněte tento rozsah, vyberte buňky a klikněte pravým tlačítkem a poté vyberte Formát buněk v nabídce pravým tlačítkem a v nabídce Formát buněk zrušte zaškrtnutí políčka Zamčený rámeček pod ochrana kartu a nakonec klikněte na OK knoflík. Viz screenshot:

2. cvaknutí přezkoumání > Chraňte plech. A určete heslo k ochraně tohoto listu.

3. Klikněte pravým tlačítkem na kartu listu a vyberte Zobrazit kód z nabídky pravého tlačítka myši. Poté zkopírujte a vložte níže uvedený kód VBA do okna Kód. Viz screenshot:

Kód VBA: Zamkněte nebo ochraňte buňky po zadání nebo vstupu dat

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

Poznámka: V kódu je „A1: F8“ rozsah, který potřebujete k zadání dat; a „123“ je heslo tohoto chráněného listu. Změňte je prosím podle potřeby.

4. lis Další + Q současně zavřete Microsoft Visual Basic pro aplikace okno.

Po dokončení zadávání dat do buněk rozsahu A1: F8 se automaticky uzamknou. A pokud se pokusíte změnit jakýkoli obsah buňky tohoto rozsahu, zobrazí se dialogové okno s výzvou. Viz screenshot:


Související články:

Nejlepší nástroje pro produktivitu v kanceláři

🤖 Kutools AI asistent: Revoluční analýza dat založená na: Inteligentní provedení   |  Generovat kód  |  Vytvořte vlastní vzorce  |  Analyzujte data a generujte grafy  |  Vyvolejte funkce Kutools...
Populární funkce: Najít, zvýraznit nebo identifikovat duplikáty   |  Odstranit prázdné řádky   |  Kombinujte sloupce nebo buňky bez ztráty dat   |   Kolo bez vzorce ...
Super vyhledávání: Více kritérií VLookup    VLookup s více hodnotami  |   VLookup na více listech   |   Fuzzy vyhledávání ....
Pokročilý rozevírací seznam: Rychle vytvořte rozevírací seznam   |  Závislý rozbalovací seznam   |  Vícenásobný výběr rozevíracího seznamu ....
Správce sloupců: Přidejte konkrétní počet sloupců  |  Přesunout sloupce  |  Přepnout stav viditelnosti skrytých sloupců  |  Porovnejte rozsahy a sloupce ...
Doporučené funkce: Zaměření mřížky   |  Návrhové zobrazení   |   Velký Formula Bar    Správce sešitů a listů   |  Knihovna zdrojů (Automatický text)   |  Výběr data   |  Zkombinujte pracovní listy   |  Šifrovat/dešifrovat buňky    Odesílat e-maily podle seznamu   |  Super filtr   |   Speciální filtr (filtr tučné/kurzíva/přeškrtnuté...) ...
Top 15 sad nástrojů12 Text Tools (doplnit text, Odebrat znaky, ...)   |   50+ Graf Typ nemovitosti (Ganttův diagram, ...)   |   40+ Praktické Vzorce (Vypočítejte věk na základě narozenin, ...)   |   19 Vložení Tools (Vložte QR kód, Vložit obrázek z cesty, ...)   |   12 Konverze Tools (Čísla na slova, Přepočet měny, ...)   |   7 Sloučit a rozdělit Tools (Pokročilé kombinování řádků, Rozdělit buňky, ...)   |   ... a více

Rozšiřte své dovednosti Excel pomocí Kutools pro Excel a zažijte efektivitu jako nikdy předtím. Kutools for Excel nabízí více než 300 pokročilých funkcí pro zvýšení produktivity a úsporu času.  Kliknutím sem získáte funkci, kterou nejvíce potřebujete...

Popis


Office Tab přináší do Office rozhraní s kartami a usnadňuje vám práci

  • Povolte úpravy a čtení na kartách ve Wordu, Excelu, PowerPointu, Publisher, Access, Visio a Project.
  • Otevřete a vytvořte více dokumentů na nových kartách ve stejném okně, nikoli v nových oknech.
  • Zvyšuje vaši produktivitu o 50%a snižuje stovky kliknutí myší každý den!
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