简体   繁体   中英

Excel VBA worksheet event stuck in constant loop

I've combined two SO questions/answers to create some VBA to automatically replace special characters in a cell (E6 in this example).

It works great for replacing special characters, but when I clear the cell (Select E6 and press Delete key), it gets stuck in a constant loop.

Code below:

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

I tried adding an Else statement to block the loop from happening but it did not work:

Else

    Cells(6, 5).Select

SO Question/Answer references:

excel VBA run macro automatically whenever a cell is changed

Removing special characters VBA Excel

Can anyone provide insight on what I'm doing wrong?

Thanks!

Turn off the Event Handler before you write back to the cell. Otherwise, writing back to the cell fires the Event Handler again, and will never stop it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM