[英]Excel VBA For Loop runs multiple times
我有一個 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
代碼對我來說看起來不錯。 我想說您只是在“A”列中多次使用 userVal,因此它也會多次觸發 msgbox。
編輯:我注意到您的代碼存在於更改事件中。 當您覆蓋 Target = "" 時,我認為這可能會一遍又一遍地重新觸發整個過程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.