构建一个新的excel工作簿,并将以下代码添加到插入的module1
中。
在工作表中输入:
= Today()
中输入公式在“公式”标签中,将名称TodaysDate
定义为$F$1:$H$1
。
将工作表重命名为“测试”
在立即窗口中,键入Protect
,然后按Enter。
接下来键入FixDate
,然后按Enter。
在线发生运行时错误1004:
rng.Locked = True
请注意,范围TodaysDate
中的值已更改为消息框提供的文本,但是除非工作表不受保护,否则不能更改范围的单元格属性。我也希望更改范围TodaysDate
的颜色以匹配单元格A1的颜色。此属性更改也将在运行时1004时失败。我在构建示例时从代码中省略了尝试,使其尽可能简单。
这是一个Excel错误吗?还是错过了一些关于设置范围属性的限制?
代码如下:
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
答案 0 :(得分:0)
删除有问题的代码(rng.locked = true)并替换为 Selection.Locked =真 Selection.Interior.ColorIndex = wks.Range(Cells(1,1),Cells(1,1))。Interior.ColorIndex
此代码可以正常运行,而无需取消保护工作表。 它仍然没有解释为什么Range对象rng失败。我对此有任何评论。
谢谢