Error Handling - Runtime Error Box Still Occurring - vba

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

Related

VBA Detecting an error and stopping the code

I currently have this, but I dont necessarily need a loop. I just need to see if there is any error in the usedrange, and if yes, stop the code and display the message. If no error, then just continue with the rest of the steps that are after this part of the code. Right now this loop displays this message for every error detected. I just need it to be displayed once if any error is found, and then stop the code.
Dim r As Range
For Each r In ws_DST.UsedRange
If IsError(r.Value) Then
MsgBox "Please fix any errors", vbOKOnly
End If
Next
End
How about:
Sub errortest()
On Error Resume Next
Set Rng = Cells.SpecialCells(xlCellTypeFormulas, xlErrors)
On Error GoTo 0
If Rng Is Nothing Then
Exit Sub
Else
For Each r In Rng
MsgBox r.Address(0, 0)
Next r
End If
End Sub

excel multiple on error goto

I am trying to get multiple on error statements to work and can't figure it out.
If pdf can be found in local then open, if not then open network location. If there is no PDF in then return msgbox.
Sub Cutsheets()
Application.ScreenUpdating = False
Dim finalrow As Integer
finalrow = Cells(Rows.Count, 1).End(xlUp).Row
On Error GoTo net1
If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
'Local Location
ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub
net1:
If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
'Network Location
On Error GoTo whoa
ActiveWorkbook.FollowHyperlink "P:\Network" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub
whoa:
MsgBox ("No cutsheet can be found for this item.")
Application.ScreenUpdating = True
End Sub
Also I don't remember why I put sendkeys in there but it doesn't work without it.
Using multiple On Error Goto XYZ handlers for control flow is over-complicating some easy validation checks you can do and then simply use the error handling for actual errors.
As #Rory pointed out in a comment you can use the Dir function. You can combine the use of Dir with an If...ElseIf...Else...End If construct to control what you code does:
Option Explicit
Sub Cutsheets()
On Error GoTo ErrHandler
Dim strLocalCheck As String
Dim strNetworkCheck As String
'check for files - Dir will return "" if file not found
strLocalCheck = Dir("C:\Local" & ActiveCell.Value & ".pdf")
strNetworkCheck = Dir("P:\Network" & ActiveCell.Value & ".pdf")
'control flow
If strLocalCheck <> "" Then
ActiveWorkbook.FollowHyperlink strLocalCheck
Application.SendKeys "{ENTER}", True
ElseIf strNetworkCheck <> "" Then
ActiveWorkbook.FollowHyperlink strNetworkCheck
Application.SendKeys "{ENTER}", True
Else
MsgBox "No cutsheet can be found for this item."
End If
Exit Sub
ErrHandler:
Debug.Print "A real error occurred: " & Err.Description
End Sub
I am trying to get multiple on error statements to work
Don't.
Imagine you're the VBA runtime. You're executing a procedure called Cutsheets, and you come across this instruction:
On Error GoTo net1
From that point on, before you blow up in the user's face, you're going to jump to the net1 label if you ever encounter a run-time error. So you keep running instructions. Eventually you run this line:
ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf"
And when the FollowHyperlink method responds with "uh nope, can't do that" and raises a run-time error, your execution context changes.
You're in "error handling" mode.
So you jump to the net1 label. You're in "error handling" mode. There are certain things you can do in "normal execution mode" that you can't (or shouldn't) do in "error handling mode". Raising and handling more errors is one of these things.
On Error GoTo whoa
You're already handling a run-time error: what should you do when you encounter that statement in an error handler subroutine? Jump to the whoa right away?
When the VBA runtime is in "error handling mode", your job as a programmer is to handle runtime errors and do everything you can to get back to "normal execution mode" as soon as possible - and that's normally done with a Resume instruction, or by leaving the current scope.
Copying a chunk of code from the "normal execution path" and trying to run it (slightly altered) in "error handling mode" isn't handling errors and getting back to normal execution mode as soon as possible.
Error handling or not, copy-pasting chunks of code is poorly written code anyway.
Extract a procedure instead:
Private Sub OpenPortableDocumentFile(ByVal path As String)
On Error GoTo ErrHandler
ActiveWorkbook.FollowHyperlink path
Application.SendKeys "{ENTER}", True
Exit Sub
ErrHandler:
MsgBox "Could not open file '" & path & "'."
End Sub
Now that that's out of the way, clean up your control flow by verifying if the file exists before you pass an invalid path to the OpenPortableDocumentFile procedure.
The best error handling strategy is to avoid raising run-time errors in the first place.

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

On Error GoTo statement is still executing although there is no error generated [duplicate]

This question already has answers here:
Why VBA goes to error handling code when there is no error?
(5 answers)
Closed last year.
I have my code below, the strange thing is that the Errorhandler procedure is still executing even though there are no errors in the code... What can be the issue?
Running the code without any errorhandlers generates no errors, but still the msgbox under Errorhandler shows up when I include an error handling statement!
Code
Public Sub ExportGraphs(Optional PivotExport As Boolean)
' Exports only graphs on the "Mainwindow" sheet to a new worksheet
Dim wsh As Worksheet: Set wsh = Sheets.Add
Dim source_sht As Worksheet: Set source_sht = Sheets("Mainwindow")
ActiveWindow.Zoom = 70
On Error GoTo Errorhandler
With wsh
If source_sht.OLEObjects("Btn_CurrentTime").Object.Value = True Then
.Name = source_sht.OLEObjects("CombBox_Instruments").Object.Value & " " & source_sht.OLEObjects("DTPicker_FROM").Object.Value _
& "-" & source_sht.OLEObjects("DTPicker_TO").Object.Value
Else
.Name = source_sht.OLEObjects("CombBox_Instruments").Object.Value & " " & "Max_Possible_To" _
& "-" & source_sht.OLEObjects("DTPicker_TO").Object.Value
End If
End With
Dim source_chart As ChartObject
Dim target_rng As Range: Set target_rng = wsh.Range("A1")
For Each source_chart In source_sht.ChartObjects
source_chart.CopyPicture xlScreen, xlBitmap
target_rng.PasteSpecial
Set target_rng = target_rng.Offset(20, 0)
Next
If PivotExport = True Then
Debug.Print "se"
End If
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
#dee provided the correct answer.
The Errorhandler: is just a place holder. It does NOT operate like you think. You are using it like an If... Then... statement:
If Error Then
Show MsgBox
Else
Skip MsgBox
End If
As the Errorhandler is just a placeholder and NOT an If... Then..., the code after the placeholder will run regardless of error or no error. To rectify this issue, add an Exit Sub above the Errorhandler: line:
Exit Sub
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
In this piece of code, ErrorHandler: is what is known as a line label.
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
Line labels are not executable code, but rather just a marker that can tell other code where to jump to via any GoTo Statement. Armed with this knowledge, they are obviously not exclusive to error handlers.
The solution here is to use the Exit Statement to return from the Sub "early".
Exit Sub
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
Others may disagree with me, but I like to build my error handling so that the code always stops execution on Exit Sub. If the code ends its execution on End Sub, something has gone wrong.