简体   繁体   中英

Excel VBA For Loop runs multiple times

I have an Excel VBA code that performs more checks on the worksheet change. Everything runs fine, but I have a for loop to check for duplicates. that one runs multiple times and gives the same message box 10 or 20 times. Can you give me some hints? The complete code is:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim userVal As String
Dim LastRow As Long

'check if active column is 1
If Target.Column <> 1 Or Selection.Count > 1 Then Exit Sub

'check if cell is not empty
If Target.Value = "" Then Exit Sub

'remove points and lines
userVal = Replace(Replace(Target.Value, ".", ""), "-", "")

'check length to be 12
If Len(userVal) <> 12 Then
    Target.EntireRow.Delete
    MsgBox ("Please insert a 12-digit number")
'add points and line
Else
    userVal = Left(userVal, 4) & "." & Mid(userVal, 5, 3) & "." & Mid(userVal, 8, 3) & "-" & Right(userVal, 2)
    Target = userVal
End If

'check for duplicates
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
For i = 2 To LastRow
    If Cells(i, 1).Value = userVal Then
        Target = ""
        MsgBox ("Part number already exists at line " & i)
        If i = LastRow Then Exit Sub
    End If

Next

End Sub

Code looks fine to me. I'd say that you simply have the userVal multiple times in column "A" and thus it triggers the msgbox multiple times, as well.

EDIT: I noticed that your code lives in a change event. When you overwrite Target = "", I reckon that this might re-trigger the whole procedure over and over again.

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