[英]Excel VBA - sheet being protected too quickly
我有一个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
如果没有取消保护/重新保护工作表,宏工作正常,但添加时会生成运行时错误Application-Defined or Object-Defined error
,但不会在更改第一个单元格值Cells(r, 2).Value = "New Value"
之前生成错误Cells(r, 2).Value = "New Value"
。
我只能假设这是因为工作表在开始时没有受到保护,第一个单元格值更改在工作表被锁定之前完成(可能在一个单独的线程中运行到For循环?)。 然后宏在下一行出错,因为它试图对受保护的工作表进行更改。
如何解决此问题并防止纸张锁定太快?
您正在使用事件宏更改单元格。
你必须:
Application.EnableEvents = False
在For
循环和之前
Application.EnableEvents = True
在For
循环之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.