+ Reply to Thread
Results 1 to 19 of 19

Protected Workbooks and VBA to Unlock Them

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    05-01-2018
    Location
    Maine
    MS-Off Ver
    2010
    Posts
    114

    Protected Workbooks and VBA to Unlock Them

    Hello,

    I am at stuck with a VBA code or a workaround and would greatly appreciate any help... if its even possible with Excel. I have a list of passwords and Workbook names in a 'Master' workbook. The data is on a sheet called 'Passwords'. Column A in the 'Passwords' sheet lists some Workbook names and column B contains passwords to open the workbook. All of the password protected workbooks will stay in the same folder as the 'Master' Workbook.

    Essentially I am trying to figure out a VBA script that will search the 'Passwords' sheet. Match it up to the corresponding workbook. Unlock the workbook. And Wait.

    Separately there needs to be a code that will run that in reverse. Search 'Passwords' and replace the password on the protected workbook. This is so other macros can run through the now unlocked workbooks and then once finished, lock them again.

    I found a code through other research but it seems to not do anything when I click and im not sure this is exactly what I am needing.

    Sub Robot()
    
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Passwords")
    Dim Loc As String: Loc = "C:\Users"
    Dim pw As String, fn As String, cb As Workbook, i As Long
    
    'Loc = Local Location
    'pw = Password
    'fn = File Name
    'cb = Current Book
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
        For i = 2 To ws.Range("A" & ws.Rows.Count).End(xlUp).Row
            On Error Resume Next 'If book does not exist
                fn = Loc & ws.Range("A" & i)
                pw = ws.Range("B" & i)
    
            On Error GoTo 0
        Next i
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    
    End Sub

    Again, any help is greatly appreciated. Even if there is another way next to VBA I am open to it. It is taking to much time to start a macro (not included here) and be prompted on every workbook to enter a password. The macro errors out if you mistype the password or similar and simply takes awhile every morning when we run it. It would be a huge time saver to allow VBA to unlock them all.
    Last edited by Darkcloud617; 10-28-2019 at 04:17 PM.

  2. #2
    Forum Expert Greg M's Avatar
    Join Date
    08-16-2007
    Location
    Dublin. Ireland
    MS-Off Ver
    Office 2016
    Posts
    4,645

    Re: Protected Workbooks and VBA to Unlock Them

    Hi there,

    See if the following code does what you need:

    
    
    
    Option Explicit
    
    
    Sub Robot()
    
        Const sCOLUMN__FILENAME As String = "A"
        Const sCOLUMN__PASSWORD As String = "B"
        Const sPASSWORD_SHEET   As String = "Passwords"
        Const iFIRST_ROW_NO     As Integer = 2
        Const sFILE_PATH        As String = "C:\Users"
    
        Dim wksPasswords        As Worksheet
        Dim iLastRowNo          As Integer
        Dim sPassword           As String
        Dim sFullName           As String
        Dim sFileName           As String
        Dim iRowNo              As Integer
        Dim wbk                 As Workbook
    
        Set wksPasswords = ThisWorkbook.Worksheets(sPASSWORD_SHEET)
    
        Application.ScreenUpdating = False
    
            With wksPasswords
    
                iLastRowNo = .Range(sCOLUMN__FILENAME & .Rows.Count).End(xlUp).Row
    
                For iRowNo = iFIRST_ROW_NO To iLastRowNo
    
                    sFileName = .Range(sCOLUMN__FILENAME & iRowNo).Value
    
                    sFullName = sFILE_PATH & "\" & sFileName
    
                    If Dir$(sFullName) = sFileName Then
    
                          sPassword = .Range(sCOLUMN__PASSWORD & iRowNo).Value
    
                          Workbooks.Open Filename:=sFullName, Password:=sPassword
    
                    Else: MsgBox "The workbook """ & sFullName & """ cannot be located"
    
                    End If
    
                Next iRowNo
    
            End With
    
        Application.ScreenUpdating = True
    
    End Sub
    The highlighted values may be altered to suit your requirements.


    Regarding:


    Separately there needs to be a code that will run that in reverse. Search 'Passwords' and replace the password on the protected workbook. This is so other macros can run through the now unlocked workbooks and then once finished, lock them again.

    you say that:


    column B contains passwords to open the workbook

    so I am assuming that the structure of the workbooks is not protected. If this is the case (i.e. not protected) then it is not necessary to protect the workbooks when your routines have finished executing - when the workbooks are closed they will still need a password to be entered before they can be re-opened.


    Hope this helps - please let me know how you get on.

    Regards,

    Greg M

  3. #3
    Forum Contributor
    Join Date
    05-01-2018
    Location
    Maine
    MS-Off Ver
    2010
    Posts
    114

    Re: Protected Workbooks and VBA to Unlock Them

    Thank you for the help on this. I am extremely grateful. It is working better than my last code but it seems to have an issue locating the workbooks. It brings up the error you placed 'cannot locate XXXX workbook' on all 9 workbooks that I have. I went through and made sure that all my workbook names match the 'Password' sheet in column A, and I can still manually unlock them with the passwords in column B. My filepath is C:\Users\XXXXXXX\Documents\OneDrive. I cant really think of a reason it cannot locate them based on how the code is written.

    Again, thank you for all of the assistance and I hope you are having a wonderful day.

  4. #4
    Forum Expert Greg M's Avatar
    Join Date
    08-16-2007
    Location
    Dublin. Ireland
    MS-Off Ver
    Office 2016
    Posts
    4,645

    Re: Protected Workbooks and VBA to Unlock Them

    Hi again,

    Thanks for your feedback.

    Is there any chance that you could post your "Passwords" worksheet here? I'm more interested in the format of the workbook names than the passwords.

    Regards,

    Greg M

  5. #5
    Forum Contributor
    Join Date
    05-01-2018
    Location
    Maine
    MS-Off Ver
    2010
    Posts
    114

    Re: Protected Workbooks and VBA to Unlock Them

    Hello,

    Thank you for responding. While I cant include the actual copy of the workbooks (they contain company info all through it), I made a mock up of what I am working with. The passwords for the other workbooks are Test1 and Test2. The formula will need to go through more than just two workbooks but for testing I just included those. The sheets are also locked as they are in the original copy. Please let me know if you need anything else and I will do my best to supply it.
    Thank you again for the help. I am very grateful.
    Attached Files Attached Files

  6. #6
    Forum Expert Greg M's Avatar
    Join Date
    08-16-2007
    Location
    Dublin. Ireland
    MS-Off Ver
    Office 2016
    Posts
    4,645

    Re: Protected Workbooks and VBA to Unlock Them

    Hi again,

    Ok, I suspected what the problem might be, so that's why I asked to see the format of the workbook names as listed on the "Passwords" worksheet.

    You must include the file extension as part of the workbook name, i.e. Column A should contain values such as "Workbook1.xlsx", "Workbook2.xlsx" etc.

    I think that the problem will be solved if you amend the workbook names in this way.


    NOTE: The "Passwords" worksheet of the "Main Data Workbook.xlsm" workbook shows a workbook name and password on row one, but your original post suggests that the list of workbooks and passwords begins on row two.


    Hope this helps - as before, please let me know how you get on.

    Regards,

    Greg M

  7. #7
    Forum Contributor
    Join Date
    05-01-2018
    Location
    Maine
    MS-Off Ver
    2010
    Posts
    114

    Re: Protected Workbooks and VBA to Unlock Them

    Thank you so much for the reply. That was exactly the issue. I do have one last question though. Is it possible to have these unlock without actually opening the workbooks?

  8. #8
    Forum Expert Greg M's Avatar
    Join Date
    08-16-2007
    Location
    Dublin. Ireland
    MS-Off Ver
    Office 2016
    Posts
    4,645

    Re: Protected Workbooks and VBA to Unlock Them

    Hi again,

    Regarding:

    
    Is it possible to have these unlock without actually opening the workbooks?
    I don't think this is possible - to remove an opening-password you need to open the workbook (using the password) and then use the SaveAs method to save the workbook without an opening-password.

    Regards,

    Greg M

  9. #9
    Forum Contributor
    Join Date
    05-01-2018
    Location
    Maine
    MS-Off Ver
    2010
    Posts
    114

    Re: Protected Workbooks and VBA to Unlock Them

    Thank you so much for the assistance. This works exactly like I need it to. You are a wonderful smart intelligent person who I aspire to be

  10. #10
    Forum Expert Greg M's Avatar
    Join Date
    08-16-2007
    Location
    Dublin. Ireland
    MS-Off Ver
    Office 2016
    Posts
    4,645

    Re: Protected Workbooks and VBA to Unlock Them

    Hi again,

    Many thanks for your feedback, for the Reputation increase (much appreciated), and also for your kind words which have me blushing furiously!

    You're welcome - glad I was able to help.

    Best regards,

    Greg M

  11. #11
    Forum Contributor
    Join Date
    05-01-2018
    Location
    Maine
    MS-Off Ver
    2010
    Posts
    114

    Re: Protected Workbooks and VBA to Unlock Them

    Hello. Sorry to bring this thread up again but it turns out that the workbook unlock function is super important. Essentially we are running into an issue where we unlock the workbook and run the macro but the workbook is already locked again and we still manually type those passwords. IF we mistype one of the passwords then the macro doesnt finish and causes issues.

    In an attempt to remedy that I tried to combine the code that you made up to unlock workbooks, the code that unlocks sheets and the code that inserts data into the workbooks. I got the sheet unlock and the insert portion to work but when trying to combine the workbook unlock function it simply doesnt respond now.

    Here is what I came up with:

    Sub protect()
    '
    '
    ' this must repeat for 11 different worksheets
        
        
        Dim wb        As Workbook
        Dim ws        As Worksheet
        Dim vFile     As Variant
        Dim strPath   As String
        Dim counter   As Long
        Dim password As String
    
        Const sCOLUMN__FILENAME As String = "A"
        Const sCOLUMN__PASSWORD As String = "B"
        Const sPASSWORD_SHEET   As String = "Passwords"
        Const iFIRST_ROW_NO     As Integer = 1
        Const sFILE_PATH        As String = "C:\User\Folder1"
    
        Dim wksPasswords        As Worksheet
        Dim iLastRowNo          As Integer
        Dim sPassword           As String
        Dim sFullName           As String
        Dim sFileName           As String
        Dim iRowNo              As Integer
        Dim wbk                 As Workbook
    
    
        'set workbook unlock
        Set wksPasswords = ThisWorkbook.Worksheets(sPASSWORD_SHEET)
        
        strPath = ThisWorkbook.Path & "\"
        
        Application.ScreenUpdating = False
        
        
            'start wb unlock
                With wksPasswords
    
                iLastRowNo = .Range(sCOLUMN__FILENAME & .Rows.Count).End(xlUp).Row
    
                For iRowNo = iFIRST_ROW_NO To iLastRowNo
    
                    sFileName = .Range(sCOLUMN__FILENAME & iRowNo).Value
    
                    sFullName = sFILE_PATH & "\" & sFileName
    
                    If Dir$(sFullName) = sFileName Then
    
                          sPassword = .Range(sCOLUMN__PASSWORD & iRowNo).Value
                          
                          Workbooks.Open Filename:=sFullName, password:=sPassword
                          
                          End If
                'end wb unlock
            
                'start sheet unlock & insert block
        For Each vFile In Array("Sheet1.xlsm", "Sheet2.xlsm", "Sheet3.xlsm", "Sheet4.xlsm", "Sheet5.xlsm", "Sheet6.xlsm", "Sheet7.xlsm", "Sheet8.xlsm", "Sheet9.xlsm")
            
        Set wb = Workbooks.Open(strPath & vFile)
            
            For Each ws In wb.Worksheets    ' loop through all sheets
        
                password = "Pass1"
    
        'Check if sheet is protected and unprotect
        If ws.ProtectContents Then
    
            ws.Unprotect password
    
             End If
                
                'Insert, copy, paste
                ws.Range("L5:W5").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
                ws.Range("L5:W5").Value = ws.Range("L4:W4").Value
                ws.protect password
            Next ws
            
            wb.Close SaveChanges:=True
            counter = counter + 1
            
            'search and unlock sheets and workbook from start
            Next iRowNo
             Next vFile
        
                 End With
    
                  Exit Sub
    
            'error handling block
    err:
    
            MsgBox err.Description, "an error occured"
    
            'if the sheet isn't protected then protect it again.
            If ws.ProtectContents = False Then
    
                ws.protect password
    
                End If
    
        Application.ScreenUpdating = True
        MsgBox counter & "Processed.", vbInformation, "Done Adding"
        
    End Sub
    That was a long one and kind of messy due to my quick alterations trying to get it working. Sorry about that.

    So this code should 1. unlock the workbook 2. unlock the sheets 3. insert data in all sheets in a range on row 5 from pivot table 4. repeat until all workbooks/sheets have the data inserted 5. lock the sheets 6. lock the workbook 7. if sheets or workbooks not found or something errored then respond with error 8. let user know its completed and how many

    Let me know if I should create a new post but any help would be appreciated. Once I can get these combined and working in conjunction- my companies entire problem will be fixed.

    Thank you.
    Last edited by Darkcloud617; 11-03-2019 at 11:32 PM.

  12. #12
    Forum Expert Greg M's Avatar
    Join Date
    08-16-2007
    Location
    Dublin. Ireland
    MS-Off Ver
    Office 2016
    Posts
    4,645

    Re: Protected Workbooks and VBA to Unlock Them

    Hi again,

    Ok - now we need to be a bit more precise regarding what we're talking about.

    1) Workbook protection against opening (this is what I've been dealing with up to now);

    2) Workbook protection/locking against Structure/Windows modification, and

    3) Worksheet protection/locking against various types of change.


    If I've understood your latest post correctly, you have implemented all three types of protection in your workbooks. Can I assume that you use the same password for each type of protection (not necessarily the same password for each workbook)?

    So far, we've successfully opened workbooks which are password-protected against opening, but now you want to unprotect those opened workbooks, unprotect their worksheets, make changes to them, and then reprotect them after making those changes, is that correct?

    Are all worksheets protected, or are some of them unprotected? (All protected would be easier to handle.)

    Are opened workbooks closed by your code or are they manually closed by the Users?

    Regards,

    Greg M

  13. #13
    Forum Contributor
    Join Date
    05-01-2018
    Location
    Maine
    MS-Off Ver
    2010
    Posts
    114

    Re: Protected Workbooks and VBA to Unlock Them

    I really cannot express how much I appreciate the assistance in this. Seriously, this is a such a big help. All workbooks and sheets are locked. You've already solved the workbook opening with different passwords issue, but the code also needs to unlock the sheets in those workbooks to make an adjustment (copying/inserting row). The sheets in those workbooks are all protected with the same password "Pass1", with the only option being to modify unlocked cells. Essentially these sheets are for viewing only besides a couple unlocked cells here and there.


    Hopefully I am detailing it enough but if not... Button click in the master workbook should: 1. Unlock workbooks with column A and B from its 'Passwords' sheet 2. Unlock all sheets in the now unlocked workbook (same password for all sheets 'Pass1') 3. copy/insert range as value (copies L4:W4 and inserts values to L5:W5 on all sheets) 4. Save 5. lock the sheets 6. Lock the workbooks 7. Close all workbooks except 'Master' 8. Make sure all workbooks processed.

    On the flip side, the user hits 2 buttons in the 'Master' workbook... First Button: Updates a pivot table in 'Master' with new data. Second Button (this is the macro we're working on): A) opens locked workbooks/sheets in same folder B) goes through all sheets, finds a range that is linked to pivot table and inserts its values a row below C)Saves Workbooks D)Locks all sheets/workbooks E) Closes all workbooks except 'Master' F) Confirms all workbooks processed.

    Hopefully that helps explain it a bit more. This is essentially for a formula that will be ran every morning and generate metric numbers for individuals from the previous days work. Their numbers are all linked from the 'Master' Workbook pivot table (linked to L4:W4 on all workbooks from the 'Master' pivot table). This formula will simply move that linked data down one to allow for the next days numbers. The 9 workbooks are the teams and the sheets are the individuals in those teams.

    Please let me know if I can provide any other information and truly and deeply... Thank You.

  14. #14
    Forum Expert Greg M's Avatar
    Join Date
    08-16-2007
    Location
    Dublin. Ireland
    MS-Off Ver
    Office 2016
    Posts
    4,645

    Re: Protected Workbooks and VBA to Unlock Them

    Hi again,

    Many thanks indeed for that careful explanation of your requirements.

    See if the following code helps to progress matters further. I have tried to structure the code so that the various stages are isolated from each other - this should help if you need to change the code (Sub ModifyWorkbook) which actually modifies the workbooks - i.e. you can make the changes there without needing to bother about the code which opens/unprotects/re-protects/closes the workbooks.

    
    
    
    Option Explicit
    
    
    '=========================================================================================
    '=========================================================================================
    
    
    Sub MainRoutine()
    
        Dim sProcessedWorkbooks As String
        Dim sMissingWorkbooks   As String
        Dim colWorkbooks        As Collection
        Dim wbk                 As Workbook
    
        Application.ScreenUpdating = False
    
    '       Create a Collection of all of the workbooks which have been successfully opened
            Call OpenWorkbooks(colWorkbooks:=colWorkbooks, _
                               sProcessedWorkbooks:=sProcessedWorkbooks, _
                               sMissingWorkbooks:=sMissingWorkbooks)
    
    '       Proceed only if the Collection contains at least one opened workbook
            If colWorkbooks.Count > 0 Then
    
    '           Scan through each of the opened workbooks
                For Each wbk In colWorkbooks
    
    '               Unprotect the workbook and each of its worksheets to allow modification
                    Call SetWorkbookAndWorkSheetProtection(wbk:=wbk, bProtected:=False)
    
    '                   Modify the workbook as required
                        Call ModifyWorkbook(wbk:=wbk)
    
    '               Re-protect the workbook and each of its worksheets after modification
                    Call SetWorkbookAndWorkSheetProtection(wbk:=wbk, bProtected:=True)
    
    '               Save and close the workbook
                    wbk.Close SaveChanges:=True
    
                Next wbk
    
            End If
    
        Application.ScreenUpdating = True
    
    '   Display an appropriate closing message
        Call DisplayClosingMessage(sProcessedWorkbooks:=sProcessedWorkbooks, _
                                   sMissingWorkbooks:=sMissingWorkbooks)
        
    End Sub
    
    
    '=========================================================================================
    '=========================================================================================
    
    
    Private Sub OpenWorkbooks(colWorkbooks As Collection, sProcessedWorkbooks As String, _
                              sMissingWorkbooks As String)
    
        Const sCOLUMN__FILENAME As String = "A"
        Const sCOLUMN__PASSWORD As String = "B"
        Const sPASSWORD_SHEET   As String = "Passwords"
        Const iFIRST_ROW_NO     As Integer = 2
        Const sFILE_PATH        As String = "C:\Users"
    
        Dim wksPasswords        As Worksheet
        Dim iLastRowNo          As Integer
        Dim sPASSWORD           As String
        Dim sFullName           As String
        Dim sFileName           As String
        Dim lErrorNo            As Long
        Dim iRowNo              As Integer
    
        Set wksPasswords = ThisWorkbook.Worksheets(sPASSWORD_SHEET)
    
        Set colWorkbooks = New Collection
    
        With wksPasswords
    
            iLastRowNo = .Range(sCOLUMN__FILENAME & .Rows.Count).End(xlUp).Row
    
            sProcessedWorkbooks = vbNullString
            sMissingWorkbooks = vbNullString
    
            For iRowNo = iFIRST_ROW_NO To iLastRowNo
    
                sFileName = .Range(sCOLUMN__FILENAME & iRowNo).Value
    
                sFullName = sFILE_PATH & "\" & sFileName
    
                If Dir$(sFullName) = sFileName Then
    
                      sPASSWORD = .Range(sCOLUMN__PASSWORD & iRowNo).Value
    
                      On Error Resume Next
                          lErrorNo = 0
                          Workbooks.Open Filename:=sFullName, Password:=sPASSWORD
                          lErrorNo = Err.Number
                      On Error GoTo 0
    
                      If lErrorNo = 0 Then
    
                            colWorkbooks.Add Item:=ActiveWorkbook
                            sProcessedWorkbooks = sProcessedWorkbooks & _
                                                  vbLf & vbTab & sFullName
    
                      Else: sMissingWorkbooks = sMissingWorkbooks & _
                                                vbLf & vbTab & sFullName
    
                      End If
    
                Else: sMissingWorkbooks = sMissingWorkbooks & _
                                          vbLf & vbTab & sFullName
    
                End If
    
            Next iRowNo
    
        End With
    
    End Sub
    
    
    '=========================================================================================
    '=========================================================================================
    
    
    Private Sub SetWorkbookAndWorkSheetProtection(wbk As Workbook, bProtected As Boolean)
    
        Const sPASSWORD As String = "Pass1"
    
        Dim wks         As Worksheet
    
        If bProtected = True Then
              wbk.Protect Password:=sPASSWORD
        Else: wbk.Unprotect Password:=sPASSWORD
        End If
    
        For Each wks In wbk.Worksheets
    
            If bProtected = True Then
                  wks.Protect Password:=sPASSWORD
            Else: wks.Unprotect Password:=sPASSWORD
            End If
    
        Next wks
    
    End Sub
    
    
    '=========================================================================================
    '=========================================================================================
    
    
    Private Sub ModifyWorkbook(wbk As Workbook)
    
        Const sRANGE_SOURCE As String = "L4:W4"
        Const sRANGE_TARGET As String = "L5:W5"
    
        Dim vaDataValues    As Variant
        Dim wks             As Worksheet
    
        For Each wks In wbk.Worksheets
    
            vaDataValues = wks.Range(sRANGE_SOURCE).Value
    
            wks.Range(sRANGE_TARGET).Value = vaDataValues
    
        Next wks
    
    End Sub
    
    
    '=========================================================================================
    '=========================================================================================
    
    
    Private Sub DisplayClosingMessage(sProcessedWorkbooks As String, _
                                      sMissingWorkbooks As String)
    
        Dim sMessage_Processed  As String
        Dim sMessage_Missing    As String
        Dim sMessage            As String
    
        If sProcessedWorkbooks <> vbNullString Then
    
            sMessage_Processed = "The following workbooks have been " & _
                                 "successfully processed:" & _
                                  vbLf & _
                                  sProcessedWorkbooks
        End If
    
        If sMissingWorkbooks <> vbNullString Then
    
            sMessage_Missing = "The following workbooks could not be processed/located:" & _
                                vbLf & _
                                sMissingWorkbooks
    
        End If
    
        sMessage = sMessage_Processed
    
        If sMessage <> vbNullString And _
           sMessage_Missing <> vbNullString Then
    
            sMessage = sMessage & vbLf & vbLf & vbLf
    
        End If
    
        sMessage = sMessage & sMessage_Missing
    
        If sMessage = vbNullString Then
            sMessage = "No workbook names were listed for opening"
        End If
    
        MsgBox sMessage, vbInformation, " Operation completed"
    
    End Sub
    The highlighted values may be altered to suit your requirements.


    Hope this helps - as always, please let me know how you get on.

    Also, please feel free to ask for any further information or explanation you need.

    Regards,

    Greg M

  15. #15
    Forum Contributor
    Join Date
    05-01-2018
    Location
    Maine
    MS-Off Ver
    2010
    Posts
    114

    Re: Protected Workbooks and VBA to Unlock Them

    Thank you. This looks complicated and looks like you spent some time so I wish I could give you double reputation or something. Everything is working like it should but the insert function seems to have changed (probably a simple fix but ive never seen an insert code written like this one). It is this part of the 'ModifyWorkbook' Private sub:

        For Each wks In wbk.Worksheets
    
            vaDataValues = wks.Range(sRANGE_SOURCE).Value
    
            wks.Range(sRANGE_TARGET).Value = vaDataValues
    It is pasting over the data that is already in range L5:W5 but it should just move the data already in L5:W5 down one row. Sorry if didn't properly explain, but that should insert the range from L4:W4 to L5:W5, moving the data that was in L5:W5 to the next row down (copying L4:W4 and inserting it a row below instead of appearing over the data already in L5:W5... creating a long list in L:W eventually). Essentially we do not want to lose the data in L:W when this macro is ran and instead just keep pushing the data further down.

  16. #16
    Forum Contributor
    Join Date
    05-01-2018
    Location
    Maine
    MS-Off Ver
    2010
    Posts
    114

    Re: Protected Workbooks and VBA to Unlock Them

    Actually. I got that issue corrected. I just added

                wks.Range("L5:W5").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
                wks.Range("L5:W5").Value = wks.Range("L4:W4").Value
    In place of the pasting script that was included. After changing the reference it seems to be working flawlessly. I know ive said it multiple times already but I cannot express how much I appreciate your help. I would have never been able to come up with a code that does all this and works so quickly/error free. I dont know what you do as your profession but you should definitely consider doing this as a career.

  17. #17
    Forum Expert Greg M's Avatar
    Join Date
    08-16-2007
    Location
    Dublin. Ireland
    MS-Off Ver
    Office 2016
    Posts
    4,645

    Re: Protected Workbooks and VBA to Unlock Them

    Hi again,

    Ok on moving any existing values "downwards" before copying the new values - I did think it was a bit strange to just overwrite the existing values, but maybe I hadn't read your description carefully enough!

    The following version of the "ModifyWorkbook" routine should do what you need:

    
    Private Sub ModifyWorkbook(wbk As Workbook)
    
        Const sRANGE_SOURCE As String = "L4:W4"
        Const sRANGE_TARGET As String = "L5:W5"
    
        Dim vaDataValues    As Variant
        Dim wks             As Worksheet
    
    '   Scan through each of the (now unprotected) worksheets in the argument workbook
        For Each wks In wbk.Worksheets
    
            With wks
    
    '           Insert a new row immediately above the row which contains the Target range
                .Range(sRANGE_TARGET).EntireRow.Insert
    
    '           Assign the values from the Source range to an array
                vaDataValues = .Range(sRANGE_SOURCE).Value
    
    '           Assign the values from the above array to the Target range
                .Range(sRANGE_TARGET).Value = vaDataValues
    
            End With
    
        Next wks
    
    End Sub
    I think you may now appreciate the approach of structuring the code in dedicated "chunks" - i.e. only a single, easily-identifiable routine needed to be modified, instead of digging around inside an "overall" routine to identify which portions needed changes.

    Also, the "copy and paste" method I used (assigning source range values to an array and then assigning those array values to a target range) is fairly efficient, and has the added slight advantage of not leaving the "pasted" area highlighted after the operation.


    Hope this helps - as always, please let me know how you get on.

    Regards,

    Greg M

  18. #18
    Forum Expert Greg M's Avatar
    Join Date
    08-16-2007
    Location
    Dublin. Ireland
    MS-Off Ver
    Office 2016
    Posts
    4,645

    Re: Protected Workbooks and VBA to Unlock Them

    Hi again,

    Regarding:


    I dont know what you do as your profession but you should definitely consider doing this as a career.

    I'm a retired electrical (HV) engineer, who used (and more importantly, enjoyed using!) Excel for many aspects of my work.

    I'm delighted to have helped you out - I get quite a buzz out of saving people time when they use their computers more efficiently - after all, computers are supposed to make life easier for us!

    Regards,

    Greg M

  19. #19
    Forum Contributor
    Join Date
    05-01-2018
    Location
    Maine
    MS-Off Ver
    2010
    Posts
    114

    Re: Protected Workbooks and VBA to Unlock Them

    Good Day Greg. The code above works wonderfully but I had a quick question. I was informed to implement a new feature in our workbook (I got the other feature working) but it requires this code to have a very small change that I am having issues changing on my own. Essentially when the worksheets are locked again, it needs to leave the option 'Format Columns' checked. This is because the user has an option now that lets them change the column size. All other options can stay locked.

    I am pretty sure this part of the code

    Call SetWorkbookAndWorkSheetProtection(wbk:=wbk, bProtected:=True)
    is what needs altered but I am unsure how to have VBA differentiate what options are locked and which are unlocked. They should only be able to 'select unlocked cells' and 'format columns'. If its a big change then I can definitely just create a new post but I think it could be a relatively simple change.

    Thank you for all of your help. Seriously. You have saved my company so much time already its almost unreal.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. How do i unlock protected worksheets?
    By jamesbialek in forum Excel Formulas & Functions
    Replies: 1
    Last Post: 09-06-2005, 12:05 PM
  2. [SOLVED] How do I unlock a protected worksheet
    By Michael in forum Excel Formulas & Functions
    Replies: 4
    Last Post: 09-06-2005, 11:05 AM
  3. How do i unlock protected worksheets?
    By jamesbialek in forum Excel Formulas & Functions
    Replies: 0
    Last Post: 09-06-2005, 02:05 AM
  4. How do I unlock a protected worksheet:password protected
    By Terry Swift in forum Excel Formulas & Functions
    Replies: 2
    Last Post: 08-01-2005, 09:05 PM

Tags for this Thread

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1