2017-08-22 68 views
1

我們使用SQL Server,Access和Excel自動化了我們的報告流程。然而,我們的一個疑問在早上運行有困難。有時會出現超時錯誤。發生這種情況時,整個系統出現故障,我們必須手動繼續處理。VBA如果再次嘗試錯誤

我一直希望添加一個VBA循環,以便查詢在發生失敗時再次嘗試。

我希望系統:

  1. 運行查詢。
  2. 如果失敗,請等待5分鐘後再試。
  3. 如果連續失敗5次,請停止該代碼。

我寫了下面的代碼,但我沒有辦法測試它。我希望你們中的任何一個人都能檢查出來,並評論它是否應該起作用。

'Counter for the errors 
    ErrorCount = 0 
    GoTo CheckConnection 

CheckConnection: 
    If ErrorCount < 6 Then 
    'Try to execute the query 
     db.Execute sqlq 
     'If it fails, ignore the error message and go to BadConnection 
     On Error GoTo BadConnection 
    Else 
    'If the query failed 5x, just give up and show the error message 
     db.Execute sqlq 
     Resume Next 
     End If 

BadConnection: 
    'Add +1 to the counter 
     ErrorCount = ErrorCount + 1 
     'Allow the application to wait for 5 minutes 
     Application.Wait (Now + TimeValue("0:05:00")) 
     'Try the query again 
     GoTo CheckConnection 

回答

1

你是不是在正確的位置恢復,它需要在錯誤處理代碼:

'Counter for the errors 
    ErrorCount = 0 
    GoTo CheckConnection 'This statement is pointless if the label is directly after it 

CheckConnection: 
    'Try to execute the query 

    ' This says to go to BadConnection if an error occurs after it, 
    ' not if an error occurred previously 
    On Error GoTo BadConnection 
    db.Execute sqlq 
    ' Start allowing errors to crash Excel again 
    On Error GoTo 0 
    'Query worked - continue processing 
    '.... 

    '... 
    Exit Sub 

'Error handling code  
BadConnection: 
    ' Start allowing errors to crash Excel again 
    On Error GoTo 0 
    If ErrorCount = 5 Then 
     'If the query failed 5x, just give up and show the error message 
     MsgBox "Giving up" 
     Exit Sub 
    End If 
    'Add +1 to the counter 
    ErrorCount = ErrorCount + 1 
    'Allow the application to wait for 5 minutes 
    Application.Wait (Now + TimeValue("0:05:00")) 
    'Try the query again by Resuming at CheckConnection 
    Resume CheckConnection 
+0

謝謝你,我在Excel中測試了一個基本的除以0的錯誤,它的作用就像一個魅力。我的VBA不是最強大的,所以這絕對有幫助。 – TheNiers

0

這是不能夠制定出使用遞歸可選參數

Option Explicit 

Public Sub TestMe(Optional errorCount As Long = 0) 

    On Error GoTo TestMe_Error 

    'Your code just to test it, make an error 
    Debug.Print errorCount/0 

    On Error GoTo 0 
    Exit Sub 

TestMe_Error: 

    Debug.Print "Error " & Err.Number & " (" & Err.Description & ") in procedure TestMe" 
    errorCount = errorCount + 1 

    Select Case errorCount 

     Case 1, 2, 3 
      Application.Wait Now + #12:05:00 AM# 
      Call TestMe(errorCount) 

     Case Else 'The 5th time it exits 
      Exit Sub 

    End Select 

End Sub 

遞歸時,重新運行代碼。代碼重新運行的時間保存在參數errorCount中。因此,它退出的時間。

一般而言,請避免GoTo並僅將其用於錯誤處理。 GOTO still considered harmful?

+0

我不會在這裏使用遞歸。簡單的'wait'和'resume'在我看來更簡單。 –

+0

@PatrickHonorez - 等待並恢復代碼對我來說變得有點意大利麪。但如果它真的是一條多達100行的小片段,那麼任何事情都可以。 – Vityata

相關問題