【发布时间】: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
【问题讨论】: