简体   繁体   English

Excel VBA - 表格保护太快

[英]Excel VBA - sheet being protected too quickly

I have a VBA macro that loops through cells whose values have been changed and amends the values of other cells in the same row. 我有一个VBA宏,循环通过其值已更改的单元格,并修改同一行中其他单元格的值。

Public Sub Worksheet_Change (ByVal Target As Range)
    Dim r As Integer
    Application.ScreenUpdating = false
    ' Unprotect the sheet
    ActiveSheet.Unprotect("password")

    Set newRange = Range("K:K")

    If Not Application.Intersect(newRange, Range(Target.Address)) Is Nothing Then
        For Each cell in Target.Cells       
            ' Change the values of cells in the same row
            r = cell.Row

            Cells(r, 2).Value = "New Value"
            Cells(r, 3).Value = "New Value"   ' Debug highlights this line
            Cells(r, 4).Value = "New Value"
            Cells(r, 5).Value = "New Value"

        Next


    End If

    ' Reprotect the sheet
    ActiveSheet.Protect Password:="password", AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True, _
        AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True
    Application.ScreenUpdating = True

End Sub

Without unprotecting/reprotecting the sheet the macro works fine, but when added it generates a Runtime Error Application-Defined or Object-Defined error , but not before changing the first cell value Cells(r, 2).Value = "New Value" . 如果没有取消保护/重新保护工作表,宏工作正常,但添加时会生成运行时错误Application-Defined or Object-Defined error ,但不会在更改第一个单元格值Cells(r, 2).Value = "New Value"之前生成错误Cells(r, 2).Value = "New Value"

I can only assume that this is because the sheet is unprotected at the start and the first cell value change completes before the sheet is then locked (perhaps running in a separate thread to the For loop?). 我只能假设这是因为工作表在开始时没有受到保护,第一个单元格值更改在工作表被锁定之前完成(可能在一个单独的线程中运行到For循环?)。 The macro then errors at the following line because it is trying to make a change to a protected sheet. 然后宏在下一行出错,因为它试图对受保护的工作表进行更改。

How can I fix this and prevent the sheet from locking too quickly? 如何解决此问题并防止纸张锁定太快?

You are changing cells with the event macro. 您正在使用事件宏更改单元格。

You must: 你必须:

Application.EnableEvents = False

before the For loop and For循环和之前

Application.EnableEvents = True

after the For loop. For循环之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM