2013-09-27 53 views
3

我有一個腳本,查看整個列,並尋找1 - 9之間的值,如果它遇到一個數字,它會拋出一個消息框,如果它不它目前拋出10個消息框,我知道這是因爲第二個框仍然在循環中。MsgBox出現多次...重新排列宏,所以它只顯示一次

我已經試過把它放在循環外,但沒有成功,任何指針會很棒,以獲得Else:MsgBox「所有位置正確輸入」來顯示一次!

Sub Scoring() 
Dim FindString As String 
Dim rng As Range 
Dim startVal As Integer, endVal As Integer 

startVal = 1 
endVal = 9 

For i = startVal To endVal 
    FindString = CStr(i) 
    With Sheets("Scoring").Range("S:S") 
     Set rng = .Find(What:=FindString, _ 
       After:=.Cells(.Cells.Count), _ 
       LookIn:=xlValues, _ 
       LookAt:=xlWhole, _ 
       SearchOrder:=xlByRows, _ 
       SearchDirection:=xlNext, _ 
       MatchCase:=False) 
     If Not rng Is Nothing Then 
      MsgBox "There are one or more risks that do not contain the minimum  information required for import, please ammend these and try again.", True 
      Exit For 
     Else: MsgBox "All locations correctly entered" 

     End If 
    End With 
Next i 

End Sub 

回答

3

可以引入存儲真正一個boolean類型的變量。任何布爾變量默認爲false,因此found默認等於false(您沒有明確說明found = false但它是可選的)。所以,你只需要將其值改爲truerng不是什麼都沒有。在退出循環之前添加了found = true

除非它是真實的,否則它總是假的是合乎邏輯的。所以當這些值匹配時,你可以切換變量狀態。

宏代碼的底部有一個額外的行,用於檢查found是否爲false。如果是,則會顯示一個消息框而不是10+。

希望這有助於

Sub Scoring() 
Dim FindString As String 
Dim rng As Range 
Dim startVal As Integer, endVal As Integer, i As Long 

startVal = 1 
endVal = 9 

Dim found As Boolean 

For i = startVal To endVal 
    FindString = CStr(i) 
    With Sheets("Scoring").Range("S:S") 
     Set rng = .Find(What:=FindString, _ 
       After:=.Cells(.Cells.Count), _ 
       LookIn:=xlValues, _ 
       LookAt:=xlWhole, _ 
       SearchOrder:=xlByRows, _ 
       SearchDirection:=xlNext, _ 
       MatchCase:=False) 
     If Not rng Is Nothing Then 
      MsgBox "There are one or more risks that do not contain the minimum  information required for import, please ammend these and try again.", True 
      found = True 
      Exit For 
     End If 
    End With 
Next i 

If Not found Then MsgBox "All locations correctly entered" 

End Sub 
+0

完美...感謝這麼多,這是一個很好的清潔解決方案! – Methexis