trap access vba messages - vba

I'm developing in Access 2007 after a period doing other things and am trying to trap messages to the user. One function in a form modifies a row in a table. The relevant bits of the code are
On Error GoTo PROC_ERR
...
DoCmd.RunSQL szSQL
...
PROC_ERR:
MsgBox "Error: (" & Err.Number & ") " & Err.Description, vbCritical
The SQL statement is correct and he system pops up with a "You are about to update 1 row ..." message (number 10505). I want to trap this and replace it with my own warning message. However, my function doesn't trap an error on this message. Nor does it do so on the message that appears if the user clicks "no": "Run-time error 2501. The RunSQL action was canceled."
In VBA options I have for the moment set Error Trapping to "Break on all errors".
What am I missing here? Have I failed to set some other option in Access?

I would recommend to do not use RunSQL. It requires DoCmd.SetWarnings False, which may affect further warnings in case if it won't be followed by DoCmd.SetWarnings True, for instance after error. Also you won't be able to read quantity of affected rows.
Use
db.Execute szSQL, dbFailOnError
instead, it will allow to trap errors and analyze database state after query execution. Without dbFailOnError option errors won't be raised.

That message is not an error.
You can silent it with
DoCmd.SetWarnings False
Remember to set them on again.

Related

MS Access - Use VBA to automatically select yes for "access was unable to append all the data" error message

I am using MS access where I click a button and it will upload a large number of files to my database. I want the user to be able to click the button and then minimise the application and when they come back all files are uploaded. However for a few of the files I get the error message "access was unable to append all the data to the table". This needs a user input and will not continue unless yes or no is selected.
For all these I always select yes, as I have a validation piece after this steps that will point out any issues.
Is there a way using VBA to build this yes selection into my code?
I already have the following in my code:
DoCmd.SetWarnings = False
DoCmd.RunSQL ...
DoCmd.SetWarnings = True
Thanks in advance,
Here is a function I use to execute sql, it returns the number of records effected by the SQL statement. It uses the 'On Error Resume Next' to handle any errors raised (not the best of coding practices). The function returns a 0 - it failed, if more then that's the number of recs effected by the SQL statement.
Function execSQL(vSQL) As Long
On Error Resume Next
Dim dbF As DAO.Database
Dim lngRecs As Long
DoCmd.SetWarnings False
Set dbF = CurrentDb
dbF.Execute vSQL
lngRecs = dbF.RecordsAffected
execSQL = lngRecs
DoCmd.SetWarnings True
dbF.Close
Set dbF = Nothing
End Function
Failing that, it may be better to use dao to execute the sql instead and then you can error trap properly on that and move on to the next record.
You could do something like this:
Sub MySub()
Dim strSql As String, fileName As String
On Error GoTo Err_MySub
'loop thru all files
strSql = "...'" & fileName & "' ...."
CurrentDb.Execute strSql
'end of loop
Exit Sub
Err_MySub:
Debug.Print fileName & " gives this error:" & Err.Description
End Sub
Press Ctrl-G to show the debug window. Maybe you should do something more clever in the error handler.
Action queries should be run using the Execute() method. No warnings of any kind are raised.
No parameters:
Currentdb().QueryDefs("QueryName").Execute dbFailOnError
With parameters:
With Currentdb().QueryDefs("QueryName")
.Parameters("ParameterName").Value = ParameterValue
.Execute dbFailOnError
End With
The dbFailOnError option will generate a run-time error if the query fails for whatever reason, so make sure your method handles errors. Lastly, if you need to see the records affected, check the RecordsAffected property of the query.

Run-Time Error 6069

Hello guys i have loop which opens for me Inline Shape (xlsx file attached in doc). It works fine but sometimes i get an error:
Run-time error 6069
It informs that i try to open excel application and probably it's not installed (WOW). When i debug it highlights a lane
wddoc.InlineShapes(lShapeCnt).OLEFormat.Activate
I press "Run" and it works normally like there was no error.
But it's frustrating cause i need to interfere and user who will use this tool can't do that.
It may be some timeout issue. You may try to repeat operation for a while:
...
timeout = Now + #00:00:01# 'Try for 1 second max
On Error Resume Next
Do
Err.Clear
wddoc.InlineShapes(lShapeCnt).OLEFormat.Activate
Doevents 'Sometimes you need to allow events to succeed in some methods
Loop While Err.Number=0 Or Now>timeout
If Err.Number <> 0 Then
MsgBox "Coudn't make call..."
Err.Raise Err.Number
End If
On Error GoTo 0 'or whatever error handler you were using
...

On Error During Loop

I have this code setup which inserts data into a table from another, and it is setup on a loop. I would like for it to check to see if the record it was supposed to upload actually uploaded and if it didn't I would like for it to try again, then after the second try if it still cant I would like for it to terminated the code. Basically:
Before this code runs a connection check is run prior then if there is a connection the record uploads, then during the loop process I would like for it to run a select statement to find the record that was just uploaded on the new table. If it finds it, then it continues onto the next record, if it doesn't it tries one more time, then stops if it still cant. This is one way for me to verify the connection.
It is a way to kind of test the connection during the actual upload process so I don't have to build in a connection check after each record, thus saving time. I am just unsure how to build in an On Error in a loop, are there any ideas? The bottom of the code looks like:
qdf.ReturnsRecords = False
On Error GoTo Update_qdfError
qdf.Execute dbFailOnError
On Error GoTo 0
rs.MoveNext
Loop
rs.Close
Set qdf = Nothing
Set cdb = Nothing
Set rs = Nothing
Exit Function
Update_qdfError:
For Each err In DAO.Errors
MsgBox err.Description, vbCritical, "Error " & err.Number
Next
End Function
Since VBA doesn't have structured error handling, you would do the error testing one line at a time in your loop by setting the On Error property and then checking the ERR object. First, set it up so it falls over to the next line of code like this.
On Error Resume Next
Then, test.
Do While rs.EOF
rs.Fields("fieldName").value =value
if Err.Number >0 then
'you had an error
end if
Loop

MS Access - execute a saved query by name in VBA

How do I execute a saved query in MS Access 2007 in VBA?
I do not want to copy and paste the SQL into VBA. I rather just execute the name of the query.
This doesn't work ... VBA can't find the query.
CurrentDb.Execute queryname
You can do it the following way:
DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit
OR
CurrentDb.OpenRecordset("yourQueryName")
You should investigate why VBA can't find queryname.
I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute.
CurrentDb.Execute "qryAddLoginfoRow"
My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.
Edit:
You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute line.
Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name
The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb to Execute.
To use CurrentDb.Execute, your query must be an action query, AND in quotes.
CurrentDb.Execute "queryname"
Thre are 2 ways to run Action Query in MS Access VBA:
You can use DoCmd.OpenQuery statement. This allows you to control these warnings:
BUT! Keep in mind that DoCmd.SetWarnings will remain set even after the function completes. This means that you need to make sure that you leave it in a condition that suits your needs
Function RunActionQuery(QueryName As String)
On Error GoTo Hell 'Set Error Hanlder
DoCmd.SetWarnings True 'Turn On Warnings
DoCmd.OpenQuery QueryName 'Execute Action Query
DoCmd.SetWarnings False 'Turn On Warnings
Exit Function
Hell:
If Err.Number = 2501 Then 'If Query Was Canceled
MsgBox Err.Description, vbInformation
Else 'Everything else
MsgBox Err.Description, vbCritical
End If
End Function
You can use CurrentDb.Execute method. This alows you to keep Action Query failures
under control. The SetWarnings flag does not affect it. Query is executed always without warnings.
Function RunActionQuery()
'To Catch the Query Error use dbFailOnError option
On Error GoTo Hell
CurrentDb.Execute "Query1", dbFailOnError
Exit Function
Hell:
Debug.Print Err.Description
End Function
It is worth noting that the dbFailOnError option responds only to data processing failures. If the Query contains an error (such as a typo), then a runtime error is generated, even if this option is not specified
In addition, you can use DoCmd.Hourglass True and DoCmd.Hourglass False to control the mouse pointer if your Query takes longer

Stuck with some weird error in VBA

I am doing project in powerpoint 2007 automation. In that i am using macro programming (VBA). I am getting the following error while run the macro.
Err.Number= -2147024809 (80070057)
but my concern is not with error Because i want to catch this error and base on this error i want to perform some action.
Thats why i try to code like this for error handing code:
OnError Goto Err:
'some code
Err:
If Err.number = -2147024809 (80070057) then
'do something
end if
Resume next
So bascially if i write error number in this way then its not allow it. it gives error.
and major thing is when error occurs sometime it did not go to "Err : ". It just pop-up error with "End" and "Debug" options.
While it seems to work, I'd be cautious about using a reserved object name (Err) as a label, for one thing.
On Error GoTo ErrorHandler
' Your code here
' Make sure you don't hit the errorhandler when there's
' no error:
NormalExit:
Exit Sub ' or Function, whichever this is
ErrorHandler:
If err.Number = 123456788 Then
' Take corrective action
' then continue
Resume Next
End If
' Trap other specific or general errors here
' Then make sure you know where you're going to exit:
Resume NormalExit
If you need to trap very specific errors that might occur only at certain places in your code, you can also do a local errorhandler:
On Error Resume Next
' Some code that might cause problems
' Did it throw the error you're trying to trap?
If Err.Number = 12398745 then
' Corrective action
End If
' And now we return to our regularly scheduled error trapping
On Error GoTo ErrorHandler
Error numbers are numeric: -2147024809, its just displayed to you as the string "-2147024809 (80070057)" for clarity (80070057) being the error number in hexadecimal.
You want;
if err.number = -2147024809 then ....
or if you so choose
if err.number = &h80070057 then ....
The 80070057 part of the error message is the unsigned hexadecimal version of the negative number -2147024809. Remove that part of your code and you will be fine, if you want to keep track of the hex version of the number (can be useful for researching errors via Google etc) then just add it as a comment.