首页 > 解决方案 > 保护工作表时出现 VBA 运行时错误 1004

问题描述

以下代码旨在在受保护的工作表上运行,但是当我在运行代码后重新保护它时,在具有 Range 或 Cell 的代码行上出现错误 1004“应用程序定义或对象定义错误”。如果我之后不重新保护工作表,我不会收到此错误。有什么帮助吗?

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim KeyCells, KeyCells2 As Range

    With Sheets(2)
        .Unprotect Password:="xyz"
        Set KeyCells = .Range("U5")
        If Not Application.Intersect(KeyCells, .Range(Target.Address)) Is Nothing Then
            lastrow = FindLastRow("*")
           .Range("T8:T" & lastrow) = .Range("U5")
            For i = 8 To lastrow
                If .Cells(i, "R") > .Cells(i, "T") Then
                    .Cells(i, "U").Value2 = IIf(.Cells(i, "R") > .Cells(i, "S"), Cells(i, "R"), Cells(i, "S"))
                Else
                    .Cells(i, "U").Value2 = IIf(.Cells(i, "T") > .Cells(i, "S"), .Cells(i, "T"), Cells(i, "S"))
                End If
            Next i
        End If
    End With

    Call PS3.ProtectSheet

End Sub

标签: vbaexcel

解决方案


推荐阅读