Forum Discussion

scottbaker1976's avatar
scottbaker1976
Copper Contributor
Jul 12, 2023

Excel cell protection / lock

I have a shared excel spreadsheet that many people have access to and need to add data to.  Can I set the spreadsheet to automatically lock cells (rows) once someone has added data and saved the spreadsheet (ie so the data that has been added can't be removed)

 

Thanks

1 Reply

  • H2O's avatar
    H2O
    Iron Contributor
    You has a shared Excel spreadsheet that many people have access to and need to add data to. You wants to set the spreadsheet to automatically lock cells (rows) once someone has added data and saved the spreadsheet, so that the data that has been added cannot be removed.

    Excel cell protection and locking are features that allow you to prevent unauthorized changes or deletion of data in your workbook. You can protect a whole worksheet, a range of cells, or individual cells. You can also set a password to unprotect the worksheet or cells, or allow certain users to edit specific ranges.

    To automatically lock cells after data entry, you can use a macro that runs when the worksheet is saved. A macro is a set of instructions that can automate tasks or perform actions in Excel. You can write your own macro using Visual Basic for Applications (VBA), a programming language that is integrated with Excel. You can also record a macro using the Macro Recorder, which captures your keystrokes and mouse clicks as VBA code.

    Here is an example of a macro that locks the cells in column A after data entry and saves the worksheet with a password:

    ```vba code

    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim rng As Range
    Dim cell As Range
    Set rng = Range("A:A")
    For Each cell In rng
    If cell.Value <> "" Then
    cell.Locked = True
    End If
    Next cell
    ActiveSheet.Protect Password:="1234", UserInterfaceOnly:=True
    End Sub

    ```

    This macro should be placed in the ThisWorkbook module in the Visual Basic Editor. To access the Visual Basic Editor, press Alt+F11 on your keyboard. To insert the macro in the ThisWorkbook module, double-click on ThisWorkbook in the Project Explorer window, and paste the code in the code window.

    You can modify this macro to suit your needs, such as changing the range, the password, or adding other conditions or actions. You can also learn more about macros and VBA from various online resources, such as [Microsoft Docs], [Excel Easy], [Excel Jet], etc.

    I hope this information helps you understand more about Excel cell protection and locking and how to use macros to automate them.

Resources