Build a new excel workbook and add the following code to an inserted module1
.
In the worksheet enter:
- "Test FixDate" to cell A1.
- Merge and Center cells F1:H1.
- Unlock Cells F1.
- Enter formula in F1
= Today()
In the Formula Tab Define Name TodaysDate
as $F$1:$H$1
.
Rename the worksheet "Test"
In the Immediate window type Protect
and press Enter.
Next type FixDate
and press Enter.
A run-time error 1004 occurs on line:
rng.Locked = True
Note that the value in Range TodaysDate
is changed to the text provided by the message box, but the cell properties of the range cannot be changed unless the worksheet is unprotected. I wish to change the color of the range TodaysDate
to match the color of Cell A1, too. This property change also fails with run-time 1004. I have omitted the attempt from the code in building the example to be as simple as possible.
Is this an Excel bug? or have I missed some restriction about setting the range properties?
Here is the code:
Option Explicit
Global Const gPassword As String = "password"
Sub FixDate()
Dim rng As Range
Dim wks As Worksheet
Set wks = Worksheets("Test")
wks.Activate
Set rng = Range("TodaysDate")
If ActiveWorkbook.FileFormat <> xlOpenXMLTemplateMacroEnabled _
And ActiveWorkbook.FileFormat <> xlOpenXMLTemplate _
And ActiveWorkbook.FileFormat <> xlTemplate Then
If Not rng.Locked Then
' Let user change the date; today's date is default
rng.Value = InputBox("Enter competition date (mm/dd/yy), if not today.", Range("A1"), Format(Now(), "mm/dd/yy"))
rng.Copy
rng.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
rng.Locked = True
End If
End If
Application.Goto Reference:=rng, Scroll:=False
Set rng = Nothing
Set wks = Nothing
End Sub
Public Sub ProtectWorkbook(Optional UnProtect As Boolean = False)
'
' Workbook is protected (or optionally unprotected) in such a way as to allow code to change the data
' without unprotecting worksheets but human interface needs password.
'
Dim wks As Worksheet
Dim wksActive As Worksheet
Dim i As Integer
Set wksActive = ActiveSheet
For Each wks In Worksheets
With wks
If .Name = "Roster" Then
On Error Resume Next
.Visible = xlSheetHidden
End If
wks.UnProtect Password:=gPassword
If UnProtect = False Then wks.Protect Password:=gPassword, UserInterfaceOnly:=True
End With
Next wks
Set wks = Nothing
wksActive.Activate
Set wksActive = Nothing
End Sub
Public Sub Protect()
ProtectWorkbook UnProtect:=False
End Sub
Public Sub UnProtect()
ProtectWorkbook UnProtect:=True
End Sub