Excel VBA工作表事件陷入常量循环

时间:2016-06-30 16:11:11

标签: excel-vba vba excel

我结合了两个SO问题/答案来创建一些VBA来自动替换单元格中的特殊字符(本例中为E6)。

它非常适合替换特殊字符,但是当我清除单元格(选择E6并按Delete键)时,它会陷入一个恒定循环。

以下代码:

Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],}"  'modify as needed

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Cells(6, 5)) Is Nothing Then

        Dim myString As String
        Dim newString As String
        Dim char As Variant

        myString = Cells(6, 5).Value
        newString = myString

        For Each char In Split(SpecialCharacters, ",")

            newString = Replace(newString, char, "")

        Next

        Cells(6, 5).Value = newString

    End If

End Sub

我尝试添加Else语句来阻止循环发生,但它不起作用:

Else

    Cells(6, 5).Select

SO问题/答案参考:

excel VBA run macro automatically whenever a cell is changed

Removing special characters VBA Excel

任何人都可以提供有关我做错事的见解吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

在写回单元格之前关闭事件处理程序。否则,写回单元格会再次触发事件处理程序,并且永远不会停止它。

Application.EnableEvents = False
Cells(6, 5).Value = newString
Application.EnableEvents = True