On Error During Loop - sql

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

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.

Automate response to Run-time error 3146 ODBC--call failed

I have a number of Excel dashboards running in my factory that refresh each minute, by connecting to a local Access Db and running a number of queries.
The Db itself has ODBC connections to a couple of different SQL database tables. They run fine most of the time but I have a problem with random 3146 ODBC--call failed errors popping up.
I have worked with my IT people and have not really been able to nail down the root cause.
I can click OK on the error popup and the dashboard may refresh fine for anther day or more or it may pop the 3146 error again 10 minutes later. There does not seem to be any real consistency to it.
I have read several posts about missing primary keys in the linked tables as to root cause. That may be true here as well but unfortunately these tables are from a third party vendor and I cannot modify them without creating issues with their software functionality.
Short of an actually fix for the root cause, I am wondering if there is a way through my VBA that I can automate clicking the OK button on the 3146 error popup so that this error is automatically acknowledged and the dashboard can go on about it's business.
One way to handle the situation is to trap the error. I can only suggest a general approach, one that I use in similar situations. Without knowing more about your app, it is hard to be very specific. This answer assumes you are using ADO to connect to Access, and pulling back a Recordset to populate the Dashboard. It further assumes you are not trapping errors currently. Here is a template to illustrate the idea:
Public Sub Dashboard()
On Error GoTo error
Dim e As ADODB.error
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = "however you are connecting"
Set rs = "however you are retrieving data" 'assuming an error with this line
Do While Not rs.EOF
rs.MoveNext
Loop
cleanup:
'any code that always has to happen
Exit Sub
error:
If Err.Number = 3146 Then
'do nothing and continue where you left off
Resume Next
End If
'possibly check connection errors, too
For Each e In cn.Errors
If e.Number = 3146 Then
'do nothing and continue where you left off
Resume Next
End If
Next
'show error and exit sub (which is what it is doing now)
MsgBox Err.Description
Resume cleanup
End Sub
Here's another option if you don't care to catch a specific error:
Public Sub Dashboard()
Dim rs As ADODB.Recordset
On Error Resume Next
Set rs = "however you are retrieving data" 'assuming an error with this line
On Error GoTo 0
Do While Not rs.EOF
rs.MoveNext
Loop
End Sub

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
...

VBA ADO: Could Not Use <Filename>; file already in use

It's been a long time since I've had to do any development in Access, so hoping I can get some help. I have a split Front End/Back End solution that I've built. The Back End resides on a server, the front end gets copied down to user's desktops (and they use runtime Access 2013). I'm using Access with VBA and ADO connections/recordsets in order to do all record actions (Select, inserts, updates mostly).
Two intermittent issues have cropped up and I'm at a loss - this is one of them. From time to time, some users will get the error "Could not use "(back end Filename)"; file already in use." (where (back end filename) is my back end db name & location". When users get this message, they close out, re-open and try the same data entry and it works without a hitch. Here's the code:
Private Sub SetProblemCode()
On Error GoTo ErrorHandler
strSQL = "SELECT Problem_Code_ID, Problem_Code, Problem_Description FROM Problem_Code ORDER BY Problem_Description"
con.Open strConString
rstProblemCode.CursorLocation = adUseClient
rstProblemCode.Open strSQL, con, adOpenForwardOnly, adLockReadOnly
cboProblemCode.RowSourceType = "Table/Query"
Set cboProblemCode.Recordset = rstProblemCode
rstProblemCode.Close
con.Close
Exit Sub
ErrorHandler:
CriticalError Err.Description, Err.Number, Me.Name, "SetProblemCode"
End Sub
The rst and con objects are defined at the global level, a practice I've used in other solutions before but I'm questioning if that's some of the problem. I'm also questioning the cursor location, type and lock type I'm using, although it seems correct - I'm not altering data, just copying a recordset to the Access combo box.
I'm hesitant to make sweeping changes when it seems like the user closes out and tries again and it works just fine. Any thoughts?

Ignore SQL Query error in Excel Macro

I have a set of queries in a EXCEL macro, that are executed when the macro is started
If, for some queries, the indicated fields don't exist in the database, executing the macro gives the following error:
Run-time error '3021': Either BOF or EOF is True, or the current record
has been deleted. requested operation requires a current record.
I want to protect the execution of the queries so that when this situation exists (lack of corresponding column in the database or any other kind of error related to the query), the macro simply continues the execution and don't output any kind of error, leaving the corresponding cell where the result supposedly would be outputted in blank.
Relevant piece of code:
Range("G7").Select
Set rs = conn.Execute("SELECT ....")
strResult = rs.Fields(0)
You need to check that BOF and EOF arent true in an if statement. Using your code above, you could do this like so:
Range("G7").Select
Set rs = conn.Execute("SELECT ....")
If Not rs.BOF and Not rs.EOF Then
strResult = rs.Fields(0)
End If