Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Protecting/locking spreadsheet stops macro working

Status
Not open for further replies.

Sam577

Technical User
Sep 2, 2003
168
GB
Hi,

I have inserted a date stamp into my spreadsheet with the following code:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim Cell As Range
For Each Cell In Target
With Cell
If .Column = Range("G:G").Column Then
Cells(.Row, "N").Value = Now()
End If
End With
Next Cell
End Sub

I want to unlock the column where the date stamp appears to prevent users from amending the time. However, after locking the relevant cells and choosing Tools>Protection>Protect Sheet in Excel, and protecting the sheet with a password, the macro stops working. Is there a way to lock / protect the date stamp values without ruining the macro? I’ve been advised to “run the macro inside Sub Auto_Close”, but I have no idea what this means? (My VB skills are elementary.) Can anyone help?

Many thanks,
Sam
 



Hi,

Your code should...

UNPROTECT
your loop
PROTECT

Skip,

[glasses] [red][/red]
[tongue]
 
First, after opening the workbook, protect the sheet again with parameter UserInterfaceOnly set to True (ThisWorkbook module):
Private Sub Workbook_Open()
ThisWorkbook.Worksheets("Name" or Index).Protect Password:="Password", UserInterfaceOnly:=True
End Sub
You can now freely change protected worksheet by code.

Secondly, your macro fires twice, you can consider disabling events:
Application.EnableEvents = False
For Each Cell In Target
...
Next Cell
Application.EnableEvents = True

combo
 
protection also plays havoc with copy and paste. Or did in the versions I used last time I tried it.

end users freak-out unless it is exactly like they always used it - hence macros are preferrable to formulae and protected sheets.
 
So I should just enclose the code with the two words UNPROTECT and PROTECT? Like this?

Private Sub Worksheet_Change(ByVal Target As Range)
UNPROTECT
Dim Cell As Range
For Each Cell In Target
With Cell
If .Column = Range("G:G").Column Then
Cells(.Row, "N").Value = Now()
End If
End With
Next Cell
PROTECT
End Sub
 



There is a specific syntax for PROTECT & UNPROTECT. It has the SHEET as an object. You may also need passwords or other parameters depending one the TYPE of sheet protection that is being used. Turn on your macro recorder to see the code required & check HELP

Skip,

[glasses] [red][/red]
[tongue]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top