我有一个循环问题。我正在开始使用它,但无法使其正常工作。
我有一个宏,它创建一个输入框以获得唯一的引用。然后,宏正在检查引用是否已在范围中使用。如果是,它将显示在何处,并要求用户使用其他参考。
我尝试了几种不同的代码,但是无法使其正常运行。即使引用不是唯一的,它也会继续执行,或者即使引用是唯一的,它也会一次又一次地循环...我认为我没有将代码放置在应有的位置。
您能帮我解决这个问题吗?
Set Rng = Range("A1:A100")
reference = InputBox("What is the reference ? (Example : UN.2019.04.31)", "Reference required")
ActiveCell.FormulaR1C1 = reference
SearchString = reference
For Each aCell In Rng
If InStr(1, aCell.Value, SearchString, vbTextCompare) Then
MsgBox "This reference is already used at line " & aCell.Address
ActiveCell.FormulaR1C1 = "REFERENCE ALREADY USED"
End If
Next
reference = InputBox("Please chose another reference.", "Reference")
Do Until Range("A" & ActiveCell.Row).Value <> "REFERENCE ALREADY USED"
For Each aCell In Rng
If InStr(1, aCell.Value, SearchString, vbTextCompare) Then
MsgBox "This reference is already used at line " & aCell.Address
ActiveCell.FormulaR1C1 = "REFERENCE ALREADY USED"
reference = InputBox("Please chose another reference.", "Reférence")
ActiveCell.FormulaR1C1 = reference
End If
Next
Loop
PS:为什么张贴之前我不能打招呼? (每次编辑时,它都会删除单词)
答案 0 :(得分:0)
满足条件时,您将缺少“退出”。例如,这是top循环的样子。
For Each aCell In Rng
If InStr(1, aCell.Value, SearchString, vbTextCompare) Then
MsgBox "This reference is already used at line " & aCell.Address
ActiveCell.FormulaR1C1 = "REFERENCE ALREADY USED"
Exit For
End If
Next