首页 > 解决方案 > 尝试锁定工作表中仅受 UserInterface 保护的单元格时出现运行时错误 1004:= True

问题描述

构建一个新的 excel 工作簿并将以下代码添加到插入的module1.

在工作表中输入:

在“公式”选项卡中,将名称定义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

标签: excelvbaruntime-error

解决方案


删除有问题的代码 (rng.locked = true) 并替换为 Selection.Locked = True Selection.Interior.ColorIndex = wks.Range(Cells(1, 1), Cells(1, 1)).Interior.ColorIndex

此代码运行正常,无需取消保护工作表。它仍然没有解释 Range 对象 rng 失败的原因。我会对此发表任何评论。

谢谢


推荐阅读