【发布时间】:2016-04-27 13:54:24
【问题描述】:
我有一个 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" 之前不会。
我只能假设这是因为工作表在开始时不受保护,并且第一个单元格值更改在工作表被锁定之前完成(可能在 For 循环的单独线程中运行?)。然后宏在下一行出错,因为它试图对受保护的工作表进行更改。
如何解决此问题并防止工作表锁定得太快?
【问题讨论】:
-
第一行:“ByVal Target As Row”应该是“ByVal Target As Range”
-
谢谢,修改了问题
-
你真的在分配
"New Value"吗?你能用你在问题中给出的确切代码重现问题吗? (当然密码除外) -
分配的值不相关。如果我分配
"New Value",它仍然会显示相同的错误。无论如何,这已经排序了。