Excel VBA – 工作表被太快保护了

我有一个VBAmacros,通过其值已更改的单元格循环,并修改同一行中的其他单元格的值。

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 

在不保护/重新保护工作表的情况下,macros可以正常工作,但是在添加时,会生成运行时错误Application-Defined or Object-Defined error ,但不会在更改第一个单元格值Cells(r, 2).Value = "New Value"之前生成错误。

我只能假设这是因为工作表在开始时是不受保护的,并且在工作表被locking之前,第一个单元格值更改完成(也许在单独的线程中运行For循环?)。 macros然后错误在下面的行,因为它试图改变一个受保护的工作表。

我怎样才能解决这个问题,并防止工作表太快locking?

你正在改变事件macros的单元格。

你必须:

 Application.EnableEvents = False 

For循环之前

 Application.EnableEvents = True 

For循环之后。