【问题标题】:Excel VBA For Loop runs multiple timesExcel VBA For Loop 多次运行
【发布时间】:2020-04-23 09:06:08
【问题描述】:

我有一个 Excel VBA 代码,可以对工作表更改执行更多检查。一切运行良好,但我有一个 for 循环来检查重复项。一个运行多次并给出相同的消息框 10 或 20 次。 你能给我一些提示吗? 完整代码为:

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

【问题讨论】:

    标签: excel loops for-loop


    【解决方案1】:

    代码对我来说看起来不错。我会说您只是在“A”列中多次使用 userVal,因此它也会多次触发 msgbox。

    编辑: 我注意到您的代码存在于更改事件中。当您覆盖 Target = "" 时,我认为这可能会一遍又一遍地重新触发整个过程。

    【讨论】:

    • 与此同时,我在下面的页面上找到了解决方案:datanumen.com/blogs/… 使用此选项似乎可以正常工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多