excel - 尝试锁定工作表中仅受 UserInterface 保护的单元格时出现运行时错误 1004:= True
问题描述
构建一个新的 excel 工作簿并将以下代码添加到插入的module1
.
在工作表中输入:
- “测试 FixDate”到单元格 A1。
- 合并和居中单元格 F1:H1。
- 解锁细胞 F1。
- F1输入公式
= Today()
在“公式”选项卡中,将名称定义TodaysDate
为$F$1:$H$1
。
将工作表重命名为“测试”
在“立即”窗口中键入Protect
并按 Enter。
下一个类型FixDate
并按 Enter。
在线出现运行时错误1004:
rng.Locked = True
请注意,Range 中的值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
解决方案
删除有问题的代码 (rng.locked = true) 并替换为 Selection.Locked = True Selection.Interior.ColorIndex = wks.Range(Cells(1, 1), Cells(1, 1)).Interior.ColorIndex
此代码运行正常,无需取消保护工作表。它仍然没有解释 Range 对象 rng 失败的原因。我会对此发表任何评论。
谢谢
推荐阅读
- java - 我可以使用哪些命令来查看详细信息
某种Java类? - sql - 内部连接三个表并从其中两个表中选择一列时,SELECT 语句不返回任何结果
- python-3.x - 为什么在 Python 中读取文件时撇号(“'”)会变成▒?
- java - Android WallpaperManager 方法“软砖化”用户的手机并导致设备无响应
- laravel-5.1 - 有什么方法可以绕过 Laravel 上的 Model::created() 事件吗?
- bash - 阻止失败的假脱机创建文件?
- qemu - 错误:不存在 DTC (libfdt) 版本 >= 1.4.2。请安装 DTC (libfdt) 开发包
- c# - 来自 Nike.com 的 Web 请求响应被禁止
- javascript - 我如何从 Rails 视图中获取ElementById
- python - ValueError:只能比较标记相同的系列对象 | 比较数据框中的值