VBA On Error GoTo suddenly stopped working - vba

I have an issue with the error handling in VBA.
The code has previously worked, but now suddenly errors are not handled by On Error GoTo statements and instead the code is crashing and giving a pop up with the error message as if On Error GoTo 0 would be active.
Here is an example of how the code structure is:
On Error GoTo logError
For d = 0 To Doclist.Count -1
On Error GoTo DownloadFailed
session.findById("wnd[0]/tbar[1]/btn[30]").press
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[0,21]").Text = filepath
On Error GoTo logError
...
DownloadFailed:
Err.Clear
On Error GoTo logError
Next d
logError:
ws1.Cells(1, 7).Value = Err.Description
Workbooks("Main.xlsm").Save
In the first iteration the On Error GoTo DownloadFailed is working as expected, but after this the code is crashing.
The error that I am getting is Run-time error '619'.
I saw on some similar post to clear the error with Err.Clear but this did nothing to my code.
In another part of the code I am using On Error Resume Next which at the same time stopped working.
As mentioned the code has worked previously so I have no idea what could be wrong.
Does anybody have experience with similar issues and any possible solutions for this?

Error Handling
The GoTo keyword is kind of reserved for the error-handling routine so this solution is strict about that.
Some contributors argue though that it is OK to use the GoTo keyword to skip a code block in a loop but I don't think it refers to doing it with On Error.
Sub ErrorTest()
Dim LogErrorFound As Boolean
Dim ErrNum As Long
On Error GoTo LogError ' start error-handling routine
For d = 0 To Doclist.Count - 1
On Error Resume Next ' defer error trapping
session.findById("wnd[0]/tbar[1]/btn[30]").press
ErrNum = Err.Number
If ErrNum = 0 Then
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[0,21]").Text = filepath
ErrNum = Err.Number
End If
On Error GoTo LogError ' resume error-handling routine; clears error
If ErrNum = 0 Then
'...
'Else ' download failed i.e. 'ErrNum <> 0'; do nothing!?
End If
Next d
ProcExit:
If LogErrorFound Then
On Error Resume Next ' defer error trapping; avoid endless loop
ws1.Cells(1, 7).Value = Err.Description
Workbooks("Main.xlsm").Save
On Error GoTo 0 ' stop error trapping
MsgBox "A log error occurred.", vbCritical
Else
MsgBox "Finished successfully.", vbInformation
End If
Exit Sub
LogError: ' continuation of the error-handling routine
LogErrorFound = True
Resume ProcExit
End Sub

While Err.Clear does clear the error object, it does not re-enable error handling like Resume or On Error GoTo 0. In order to manually do this, replace Err.Clear with On Error GoTo -1 like this:
On Error GoTo logError
For d = 0 To Doclist.Count -1
On Error GoTo DownloadFailed
session.findById("wnd[0]/tbar[1]/btn[30]").press
session.findById("wnd[1]/usr/sub:SAPLSPO4:0300/ctxtSVALD-VALUE[0,21]").Text = filepath
On Error GoTo logError
...
DownloadFailed:
On Error GoTo -1
On Error GoTo logError
Next d
logError:
ws1.Cells(1, 7).Value = Err.Description
Workbooks("Main.xlsm").Save

Related

Error Handling - Runtime Error Box Still Occurring

I'm trying to implement an error handler into my code, I've managed to create a message box if a run time error occurs but after clearing the message box the run time error box pops up. This is a snippet of my code:
combinedFilename = Application.GetOpenFilename(filter, , caption)
If combinedFilename <> "False" Then
Set combinedWorkbook = Application.Workbooks.Open(combinedFilename)
Else
MsgBox "No file was uploaded", vbExclamation
End If
Any help will be appreciated.
Many thanks
Write Err.Clear after the MsgBox.
If clears the Error. See this small sample:
Public Sub TestMe()
On Error Resume Next
Debug.Print 5 / 0 '11, because this is the number of the error.
Debug.Print Err.Number
Err.Clear
Debug.Print Err.Number '0, because the error is cleared.
End Sub

Would that be a practicable way for a kind of 'finally' block in VBA?

This sample is taken from Can I Return From The Current Event Stack In Microsoft Access VBA?
I reworked it a bit to show the idea I got from reading the mentioned article.
Sure, usually I wouldn't use GoSub at all, but in this case I see no other way.
The goal is to have clean-up code at one place in a method which will be executed in all situations, also before (re-)raising an error myself.
Sub DoSomething()
On Error GoTo CleanFail
Dim fileNumber As Long
fileNumber = FreeFile
'do stuff
'...
CleanExit:
GoSub CleanFinally
Exit Sub
CleanFinally:
On Error Resume Next
Close fileNumber
On Error Goto 0
Return
CleanFail:
If Err.Number = 53 Then
' handle "file not found" error
Resume CleanExit
Else
Dim errNumber As Long
errNumber = Err.Number
GoSub CleanFinally
Err.Raise errNumber ' rethrow
End If
End Sub

VBA - error handing for non-existent web resource (Yahoo finance)

My macro generates yahoo ticker download URL's for specific companies. I generate 3 URL's per ticker, each having a different date segment for the data download.
The problem that I have, is that data does not exist for some of the dates, hence an error is returned from Yahoo which causes my Macro to crash.
I've attempted the following with a GOTO label:-
On Error GoTo error_handler
Workbooks.Open Filename:=("http://chart.finance.yahoo.com/table.csv?s=FAN.L&a=2&b=04&c=2014&d=2&e=21&f=2014&g=d&ignore=.csv")
however this does not work, it does not GOTO the label.
Any ideas would be greatly appreciated.
Try this:
On Error Resume Next
Workbooks.Open Filename:=("http://chart.finance.yahoo.com/table.csv?s=FAN.L&a=2&b=04&c=2014&d=2&e=21&f=2014&g=d&ignore=.csv")
On Error GoTo error_handler
The On Error Resume Next will allow it to the skip ahead.
Download the file with seperate error handling and then if-check
If Dir(MyFileName) <> "" Then
Workbooks.Open Filename:="C:\123.xls"
Else
MsgBox "Spreadsheet could not be found in C:\", vbCritical + vbOKOnly, "File not found"
End If
Here is some example of error handling. Replace your code with the Debug.print 5/0 and it should work.
Public Sub ErrorHandlingExample()
On Error GoTo ErrorHandlingExample_Error
Debug.Print 5 / 0
On Error GoTo 0
Debug.Print "No error"
Exit Sub
ErrorHandlingExample_Error:
Debug.Print "Error was found - " & Err.Description
End Sub

Error handling in VBA - on error resume next

I have the following code:
ErrNr = 0
For Rw = StRw To LsRw 'ToDo speed up with fromrow torow
If Len(ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl)) = 0 Then
ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl).Interior.ColorIndex = 46
ErrNr = ErrNr + 1
End If
Next
My problem is if there is an error on the page, my code is not running after that. I think the solution should be with:
On Error Resume Next
N = 1 / 0 ' cause an error
If Err.Number <> 0 Then
N = 1
End If
But I don't know how to use this code.
It depends on what you want to do.
On Error Resume Next will ignore the fact that the error occurred. This is a great way to get your code to execute to completion, but will just about guarantee that it won't do what you want.
On Error Goto 0 is the default response. It will pop up the error message that VBA is generating
On Error Goto <label> will cause your code to jump to a specified label when an error occurs and allows you to take an appropriate action based on the error code.
The last option, On Error Goto <label> is usually the most useful, and you'll want to do some digging on how to best use it for your application.
This site is where I got the details above from, and is usually the first results that comes from Googling for "excel vba on error". I've used that reference myself a number of times.
I have interpreted your requirement as to how to handle common worksheet errors when looping through a range of cells and examining the values. If you attempt to look at a cell that contains an error (e.g. #N/A, #DIV/0!, #VALUE!, etc) you will get something like:
Runtime error '13':
Type mismatch.
These can be caught with VBA's IsError function.
Dim rw As Long
With ThisWorkbook.Sheets(TsSh)
For rw = StRw To LsRw
If IsError(.Cells(rw, 1)) Then
.Cells(rw, 1).Interior.ColorIndex = 10
ElseIf Not CBool(Len(.Cells(rw, 1).Value2)) Then
.Cells(rw, 1).Interior.ColorIndex = 46
End If
Next rw
End With
        
In the above, I am catching the cells with an error and coloring them green. Note that I am examining them for errors before I check for a zero length.
I generally try to avoid On Error Resume Next as it will try to continue no matter what the error (there are some cases where it's useful though).
The code below passes all errors out of the procedure where they can be handled on a case by case basis.
Sub test1()
Dim n As Double
On Error GoTo ERROR_HANDLER
n = 1 / 0 ' cause an error
On Error GoTo 0
Exit Sub
ERROR_HANDLER:
Select Case Err.Number
Case 11 'Division by zero
n = 1
Err.Clear
Resume Next
Case 13 'Type mismatch
Case Else
'Unhandled errors.
MsgBox "Error " & Err.Number & vbCr & _
" (" & Err.Description & ") in procedure test1."
Err.Clear
End Select
End Sub

"No cells found" error

I have this piece of code getting a "No Cells Found" error. I don't understand why if I am using on error resume next and there will be times there won't be any "INATIVE" in that column.
Intersect(.UsedRange, .UsedRange.Offset(1)).SpecialCells(12).EntireRow.Delete
where 12 can also be written as xlCellTypeVisible.
Here are the lines before and after for more clarity:
With Sheets("Temp Activos")
On Error Resume Next
.UsedRange.AutoFilter 6, "INATIVE"
On Error GoTo 0
Intersect(.UsedRange, .UsedRange.Offset(1)).SpecialCells(12).EntireRow.Delete
r = WorksheetFunction.CountA(.Range("A:A"))
.UsedRange.AutoFilter
Converting comment to answer:
The On Error GoTo 0 clears the On Error Resume Next condition. So you'll need to move the On Error GoTo 0 down until just before the End With.