Home » excel » VBA Code To Use The Password From Another Sub in Excel

VBA Code To Use The Password From Another Sub in Excel

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have two codes, one that protects all sheets which uses the password from an input box, and the second one that deletes #REF! errors. On the second code I need to unprotect the sheet first in order to delete a row. Now, I am trying to figure out how can I use the pasword from the first code to unprotect the sheet so that the second code can delete the #REF! error rows?

Not sure if is even possible, but maybe someone has had the same problem before.

Any help is appreciated.

Sub ProtectAllSheets()
    Dim pwd1 As String, pwd2 As String
    pwd1 = InputBox("Enter your password", "")
    If pwd1 = "" Then Exit Sub
    pwd2 = InputBox("Enter the password again", "")

    If pwd2 = "" Then Exit Sub

     'Checks if both the passwords are identical
    If InStr(1, pwd2, pwd1, 0) = 0 Or _
       InStr(1, pwd1, pwd2, 0) = 0 Then
        MsgBox "Please type the same password. ", vbInformation, ""
        Exit Sub
    End If

    For Each ws In ActiveWorkbook.Sheets
        If ws.ProtectContents = False = True Then
            ws.Protect Contents:=True, Scenarios:= _
                True, AllowFormattingCells:=True, AllowDeletingRows:=True, Password:=pwd1
        End If

    Next ws

    MsgBox "Sheets are protected."
End Sub



Sub DeleteRows() ' Cells which contain an Error Formula
    ActiveSheet.Unprotect pwd1

    Dim c As Long
    For c = 400 To 2 Step -1
        If IsError(Cells(c, 3)) Then
            Rows(c).EntireRow.Delete
        End If
    Next c
    ws.Protect Contents:=True, Scenarios:= _
        True, AllowFormattingCells:=True, AllowDeletingRows:=True, Password:=pwd1
End Sub
How to&Answers:

You would need to declare the variable as Public.

Public pwd1 As String

Sub ProtectAllSheets()
    'NO dim for pwd1 here
    pwd1 = InputBox("Enter your password", "")
    'your code here
End Sub

So it is available in all your procedures and functions.


But I recommend to use .Protect UserInterFaceOnly:=True
which protects the worksheet from user editing but lets VBA edit it without restrictions.

Therefore you just need to protect your sheets in the Workbook_Open() event like this:

Private Sub Workbook_Open()
    Sheets("Sheet1").Protect Password:="Secret", UserInterFaceOnly:=True
    Sheets("Sheet2").Protect Password:="Secret", UserInterFaceOnly:=True
    'Repeat with the name and password of additional sheets to be manipulated by VBA.
End Sub 

This way you don’t need to protect/unprotect for every VBA action.

For a full how-to and more information see: Speedup Excel VBA Macros with Protect UserInterFaceOnly.