保护工作表时的VBA运行时错误1004

时间:2018-05-25 17:27:31

标签: excel vba excel-vba

以下代码用于在受保护的工作表上运行,但是当我在运行代码后重新保护它时,我得到错误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

0 个答案:

没有答案