How do I handle errors in Access VBA code?

I am going to give you the answer to “How do I handle errors in Access VBA code?”

In my opinion there are 2 ways to handle errors:
1. Avoid the potential for an error to occur.
2. Handle the error in your code.

Number 1 – If you have a control on your form that normally causes users to have an error, hide it to prevent the error from even happening in the first place.

Number 2 – In your code put some error handling like:

Sub ErrorSample()
     On Error GoTo errhandler

     intCauseError = 2/0


Exit Sub
errhandler:

msgbox "You can't cannot divide by zero", vbCritical,"Error Message"

End Sub

Click this link for some more error handling samples

Here is the video:

Also here is the code from the video:

Sub ErrorSample()
Dim intX As Integer

On Error GoTo errhandler

'intX = 6 / 0
intX = 0 / 6

MsgBox intX

Exit Sub

errhandler:
Select Case Err.Number
Case 11
MsgBox "You can't divide by zero. " & Err.Number, vbExclamation, "Div By Zero - Not Allowed"
Case Else
MsgBox "you have an error " & Err.Number, vbExclamation, "Error"

End Select

End Sub

Let me know if you have any question.




By the way, if you got or are getting value from the VBA information, please give me a tip, thanks!


These posts may help answer your question too...

How To Parse A Flat File In Excel VBA

In another post I demonstrated how to access a file on your computer using the MS Office Library. Here it is if you don’t know what I’m talking about. In this post, I am going to show you how to access the file and load it into your spreadsheet. I will do the same thing […]

What Is Microsoft Access Used For?

To those of you who are asking the question of “What is microsoft access used for?” , here is my opinion. I’ve been using this program for well over 15 years, and it’s become fairly easy to deal with. Many people feel that it is hard to work with, but that’s not my experience anymore […]

How To Make An Access Select Query

Hi everyone, This is not really a VBA item, but it’s important and you will need to understand this concept when you are creating your SQL statements in VBA. In our example we have a table called “Customers”: Now we just want the customers from “London”. So we set up a select query to select […]

How To Generate A XML File With Access VBA

XML is used to structure your data. You can send a CSV file to another person, but using XML, you can structure your data in a more elegant format, and get very specific about your fields, and what data is contained within your tags (your field names). This is different than a basic CSV file […]

Tags: , , ,
Previous Post

What is the purpose of the Me keyword in Access VBA?

Next Post

How can I interact with other Office applications (Excel) using VBA in Access?

Leave a Reply

Your email address will not be published. Required fields are marked *