简体   繁体   English

Excel VBA For Loop 运行多次

[英]Excel VBA For Loop runs multiple times

I have an Excel VBA code that performs more checks on the worksheet change.我有一个 Excel VBA 代码,它对工作表更改执行更多检查。 Everything runs fine, but I have a for loop to check for duplicates.一切运行良好,但我有一个 for 循环来检查重复项。 that one runs multiple times and gives the same message box 10 or 20 times.一个运行多次并给出相同的消息框 10 或 20 次。 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.我想说您只是在“A”列中多次使用 userVal,因此它也会多次触发 msgbox。

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.当您覆盖 Target = "" 时,我认为这可能会一遍又一遍地重新触发整个过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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