正在将文本追加到单元格,但陷入循环



我的问题是我的代码不能按照我认为的方式工作。我的工作表_更改宏中有循环,在该循环中,我希望如果语句正确(MsgBox按钮按下"是"(,则该单元格中写入的内容将在该文本的末尾附加值。

但如果我运行这个宏并按Yes,单元格值在末尾有值,但MsgBox又来了,我陷入了循环。。。我是VBA编程和语法的新手。

有人能帮我解释一下我的错误吗?

代码:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rLockable As Range
Dim cl As Range
Set rLockable = Range("C13:J1000")
Set cl = Range("C13:J1000")
Set cele = Range("K13:K1000")
vardas = ActiveWorkbook.Sheets("Login").Range("O8").Value
Select Case True
Case Not Intersect(rLockable, Target) Is Nothing
'If target is within the range then do nothing
If Intersect(rLockable, Target) Is Nothing Then Exit Sub
ActiveSheet.Unprotect Password:="1234"
For Each cl In Target
If cl.Value <> "" Then
check = MsgBox("Ar áraðyti áraðà? Koreguoti áraðo nebegalësite.", vbYesNo, "Áraðo iðsaugojimas")
If check = vbYes Then
Target.Worksheet.Unprotect Password:="1234"
cl.MergeArea.Locked = True
cl.Value = cl.Value & " " + vardas
Else
cl.Value = ""
ActiveSheet.Protect Password:="1234"
End If
End If
Exit For
Next cl
Case Not Intersect(Range("K13:K1000"), Target) Is Nothing
ActiveSheet.Unprotect Password:="1234"
For Each cele In Target
If cele.Value <> "" Then
cele.Offset(0, 2).MergeArea.Value = vardas
End If
Exit For
Next cele
End Select
ActiveSheet.Protect Password:="1234"
End Sub

在更改工作表之前,您需要将enableEvent设置为false,否则工作表更改事件将再次发生。

application.enableEvents=false
'change the worksheet
application.enableEvents=true
'resets the worksheet_change event

最新更新