我有一個VBA宏,通過其值已更改的單元格循環,並修改同一行中其他單元格的值。Excel 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目標爲行」應該是「ByVal目標爲範圍」 – NiH
謝謝,修正了問題 – ryansin
你真的在賦值'「新值」嗎?你可以用你在問題中給出的確切代碼重現問題嗎? (當然密碼除外) – trincot