'How do I get the source worksheet to become password protected after a copy is made by clicking an active x button?
The code below is activated from an active x button. The code will unprotect the active workbook and worksheet, make a copy of the active worksheet, place that new sheet's tab where I want it to be placed, protect the new worksheet, and protect the workbook. It fails to protect the Source Worksheet that the copy was made from. I need the code to password protect the Last Active Sheet too (the Source Sheet the Copy was made from). Any help is greatly appreciated.
Private Sub CommandButton13_Click()
ThisWorkbook.Unprotect Password:="Password1"
ActiveSheet.Unprotect Password:="Password2"
Dim i As Long, s As String, s2 As String
s = "NEW WONDERFUL WORKSHEET"
s2 = s
ActiveSheet.Copy After:=Sheets(2)
Do While WorksheetExists(s2)
i = i + 1
s2 = s & " " & i
Loop
ActiveSheet.Name = s2
ActiveSheet.Protect Password:="Password2"
ThisWorkbook.Protect Password:="Password1"
End Sub
Solution 1:[1]
I would reorganize the code a little. First, let's search for an available sheet name s2
before removing protection. Also, I assume the code is placed in the worksheet object module and at the moment when we click on the button, the sheet with this very button is the actual active sheet, so we can call it Me
instead of ActiveSheet
. As for the passwords, let's put them as constants in the beginning to make it easier to change them if needed.
Private Sub CommandButton13_Click()
Const BookPass = "Password1"
Const SheetPass = "Password2"
Dim i As Long, s As String, s2 As String
s = "NEW WONDERFUL WORKSHEET"
s2 = s
Do While WorksheetExists(s2)
i = i + 1
s2 = s & " " & i
Loop
ThisWorkbook.Unprotect BookPass
With Me
.Unprotect SheetPass
.Copy After:=Sheets(2)
With ActiveSheet
.Name = s2
.Protect SheetPass
End With
.Protect SheetPass
End With
ThisWorkbook.Protect BookPass
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |