PDA

View Full Version : How to use On Error



clif
07-30-2011, 10:17 AM
I run the add in function by macro , but sometimes it will have the pop up message so that the process cannot be run smoothly.

How to get rid of the message by using "on Error". Is it possible for all pop up message or warning. What is the code? Thank you very much!

mikerickson
07-30-2011, 10:55 PM
Are you sure that you want to get rid of the message?
Errors can be usefully informative.
Under what conditions does the routine error and what do you want to do differently when those conditions obtain?

clif
07-30-2011, 11:45 PM
since i run the function many times in the process. Record the result in spreadsheet for each run. The error is really distrubing. If it fail to run due to some reasons, i want to record it in the spreadsheet automatically by using the macro 'error handle'. But i don't what is the code?

Aussiebear
07-31-2011, 07:20 AM
So why not fix the error that causes the popup to occur?

Kenneth Hobs
07-31-2011, 07:38 PM
As Aussiebear siad, it is best to code to not produce an error. We have no idea what your macro code is for "error handle".

Here is a method to track some error information.
Sub Test_ErrCheck()
ErrCheck 0, Worksheets("Sheet2").Range("A1")
ErrCheck 1, Worksheets("Sheet2").Range("A1")
End Sub

Sub ErrCheck(aNumber As Long, Optional eCell As Range)
Dim Msg As String
On Error GoTo ErrMsg
If aNumber <> 0 Then Err.Raise aNumber
'MsgBox "aNumber=0 so no error was generated."

Exit Sub
ErrMsg:
Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & Err.Description
'MsgBox Msg, vbSystemModal, "Error", Err.HelpFile, Err.HelpContext

If eCell Is Nothing Then Exit Sub
Set eCell = eCell.Cells(Worksheets(eCell.Worksheet.Name).Rows.Count, eCell.Column).End(xlUp).Offset(1)
eCell.Value = Err.Number
eCell.Offset(0, 1).Value = Err.Source
eCell.Offset(0, 2).Value = Err.Description
End Sub

Paul_Hossler
08-01-2011, 09:01 AM
As the others have said, it's best to handle the error, or to program for it, but this will log the errors.

Without having ANY idea of that your code is actually doing, it's hard to tell if it will work, especially if the code is running in an add in


Option Explicit
Sub MakeSomeErrors()
Dim i As Long
Dim n As Long
Dim r As Long

r = 1

On Error GoTo ErrHandle

For i = 1 To 100

'generate an error when i = 10, 20, 30, ...
If i Mod 10 = 0 Then n = 1 / 0

Next i

Exit Sub
ErrHandle:

ActiveSheet.Cells(r, 1).Value = "Error occured when i = " & i
r = r + 1
Resume Next
End Sub


Paul