Results 1 to 2 of 2

Thread: Workbook protected when using this code

  1. #1
    Junior Member
    Join Date
    Jun 2013
    Posts
    16
    Rep Power
    0

    Workbook protected when using this code

    Greetings

    This code works great but can it be altered so that when the workbook is closed the Sheets are always protected.This way whenever the workbook is opened the sheets are in protected mode

    Cheers

    Code:
    Private Sub CommandButton1_Click()
    
        Dim strPassword As String
        Const strActualPassword As String = "ABCD"
        strPassword = InputBox("Please enter the password", "Protect/Unprotect Sheet")
        
        If strActualPassword = strPassword Then
            If Me.CommandButton1.Caption = "PROTECT SHEET" Then
                Me.CommandButton1.Caption = "UNPROTECT SHEET"
                UnlockCells
                Me.Protect Password:=strPassword
            Else
                Me.CommandButton1.Caption = "PROTECT SHEET"
                Me.Unprotect Password:=strPassword
            End If
        Else
            MsgBox "Invalid Password"
        End If
        
    End Sub
    
    Sub UnlockCells()
    
        Me.Range("B10:T10,B16:T18,B24:T28").Locked = False
        
    End Sub

  2. #2
    Administrator Excel Fox's Avatar
    Join Date
    Mar 2011
    Posts
    1,402
    Rep Power
    10
    Use this in the workbook module only

    Code:
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    
        Dim wks As Worksheet
        
        For Each wks In ThisWorkbook.Worksheets
            wks.Protect "passwordhere"
        Next wks
        If Not Cancel Then
            Me.Save
        End If
        
    End Sub
    A dream is not something you see when you are asleep, but something you strive for when you are awake.

    It's usually a bad idea to say that something can't be done.

    The difference between dream and aim, is that one requires soundless sleep to see and the other requires sleepless efforts to achieve

    Join us at Facebook

Similar Threads

  1. Replies: 17
    Last Post: 05-22-2013, 11:58 PM
  2. Replies: 7
    Last Post: 05-17-2013, 10:38 PM
  3. Adding charts via code to a protected sheet
    By Rasm in forum Excel Help
    Replies: 2
    Last Post: 11-14-2012, 05:11 PM
  4. VBA Code to Open Workbook and copy data
    By Howardc in forum Excel Help
    Replies: 16
    Last Post: 08-15-2012, 06:58 PM
  5. VBA code to copy data from source workbook
    By Howardc in forum Excel Help
    Replies: 1
    Last Post: 07-30-2012, 09:28 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •