VBA Error Handling

p4nny

Board Regular
Joined
Jan 13, 2015
Messages
246
Hi

I was wondering whether there was a line of code that, On error would reattempt the step again.

Sometimes, I get a message "unable to save" sometimes which is a network issue. If I save for a second time (manually), it saves without any problems.

HTML:
thisworkbook.save

If the above line fails, then repeat this step.

thanks in advance
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
It's a long solution but it does allow you to re-try and waits between tries:

Code:
Dim startTime As Single
Dim tries As Long
Dim workbookSaved As Boolean

Const MAX_RETRIES = 5 ' Maximum number of re-tries
Const WAIT_SECONDS = 2 ' Time between tries

On Error Resume Next

tries = 0
workbookSaved = False
Do While True
    ' Should we give up?
    tries = tries + 1
    If tries > MAX_RETRIES Then Exit Do
    
    ' Try and save the workbook
    Err.Clear
    ThisWorkbook.Save
    If Err.Number = 0 Then
        workbookSaved = True
        Exit Do
    End If
    
    ' Wait 2 seconds
    startTime = Timer
    Do Until Timer - startTime > WAIT_SECONDS
        DoEvents
    Loop
Loop

' Saved?
If workbookSaved Then
    Debug.Print "Saved Successfully"
Else
    Debug.Print "Failed to save after " & MAX_RETRIES & " attempt(s)"
End If

WBD
 
Upvote 0

Forum statistics

Threads
1,223,898
Messages
6,175,272
Members
452,628
Latest member
dd2

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top