in ms-access i am running a macro that runs several queries, during the execution of a query a message box appears
"you are about to run an update.......... are you sure you want to run this query ? "
how can i automatically select for all such cases so that macro runs without human intervention.
You can turn off temporary the warnings like this:
DoCmd.SetWarnings = False
DoCmd.RunSQL ...
DoCmd.SetWarnings = True
It is generally best to use Execute in such cases in order to trap errors:
Dim db As Database, qdf As QueryDef, strSQL As String
Set db = CurrentDb
Set qdf = db.QueryDefs("Query17")
qdf.Execute dbFailOnError
Debug.Print qdf.RecordsAffected
Or
strSQL="UPDATE SomeTable SET SomeField=10"
db.Execute strSQL, dbFailOnError
Debug.Print db.RecordsAffected
Trapping errors with dbFailOnError and an error trap is more or less essential and there are a number of other useful aspects to the Execute Statement
To avoid having to write the code #Remou supplies every time you execute arbitrary SQL you could use my SQLRun function, which is designed as a dropin replacement for DoCmd.RunSQL and avoids all the problems therewith.
Related
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.
I'm getting a 2498 error and really don't understand why. I'm building a string in VBA and am getting the error with the following line of code...
DoCmd.OpenQuery qdfNew, acNormal
It happened with a very long string created to create the query so I simplified the code as much as possible and am still getting the error.
Here's the code...
Option Compare Database
Option Explicit
Dim dbsFootball As Database
Dim strInsertSQL, strSelectSQL, strIntoSQL, strFromSQL, strOrderSQL, strSQL As String
Dim qdfNew As QueryDef
Sub CreateFormattedData()
Set dbsFootball = CurrentDb()
strSelectSQL = ""
strIntoSQL = ""
strFromSQL = ""
strOrderSQL = ""
strSQL = ""
strSelectSQL = "SELECT [tbl_Raw_League_Data].[Season]"
strIntoSQL = "INTO [tbl_Manip Data]"
strFromSQL = "FROM [tbl_Raw_League_Data]" _
+ "LEFT JOIN Referees ON [tbl_Raw_League_Data].[Referee] = Referees.[Referee from Source Data]"
strSQL = strSelectSQL + " " + strIntoSQL + " " + strFromSQL + " " + strOrderSQL
On Error Resume Next ' If query doesn't exist, error won't stop execution
DoCmd.DeleteObject acQuery, "pgmqry_Create Table tbl_Manip"
On Error GoTo 0 ' Reset error handler
Set qdfNew = dbsFootball.CreateQueryDef("pgmqry_Create Table tbl_Manip", strSQL)
DoCmd.OpenQuery qdfNew, acNormal
End Sub
The source field, [tbl_Raw_League_Data].[Season], is a "Short Text" data type (field size = 7).
If I terminate the VBA code and run the query that was created by the code, it works fine with no apparent errors. However, it will never run the query from within the VBA code.
I was originally getting the error 2498 when using "INSERT INTO" for an append query, but realized that the table could as easily be recreated at code execution time.
I'm lost and would sure appreciate some ideas!
Thanks in advance,
Jason
You are passing the querydef object to DoCmd.OpenQuery when it expects a string referencing name of a stored query object. Consider using the querydef's Name property:
DoCmd.OpenQuery qdfNew.Name, acNormal
Alternatively, use .Execute command from database object using the SQL string variable, bypassing any need for querydef:
dbsFootball.Execute strSQL, dbFailOnError
Or with querydef object, as #HansUp suggests, where you simply execute directly since it is an action query:
qdfNew.Execute dbFailOnError
Do note above two options bring up the regular MS Access discussion, of using stored vs VBA string query. While the former is precompiled and runs through query optimizer caching best plan, the latter can have sql dynamically created (structural components that is like SELECT, FROM and JOIN clauses as both can use passed in parameters). From your code snippet consider saving SQL query beforehand without needing to build it in VBA on the fly, and call it with DoCmd.OpenQuery.
So I have a system built in which it sets a few different flags and so on and so forth, but one of the things I want to do is take the contents of a staging table and send it over to another table used for tracking. I'm trying to do it using an insert into loop but I simply cannot figure out how to make it work as intended.
Private Sub Form_Load()
DoCmd.SetWarnings False
DoCmd.OpenQuery ("qryDeleteEmail")
Dim db As Object
Dim rst As Object
Dim test As Object
Set db = Application.CurrentDb
Set rst = db.OpenRecordset("qryDate")
Set test = db.OpenRecordset("tblEmailTemp")
If Me.RecordsetClone.RecordCount = 0 Then
MsgBox ("No delinquent accounts. No email will be generated.")
Me.Refresh
DoCmd.Close acForm, "qryDate", acSaveNo
DoCmd.CancelEvent
Else
rst.MoveFirst
Do Until rst.EOF
rst.Edit
rst!NeedsEmail = 1
rst.Update
rst.MoveNext
Loop
'DoCmd.Requery
'rst.Close
DoCmd.RunMacro ("StagingTable")
test.MoveFirst
Do Until test.EOF
CurrentDb.Execute "Insert Into EmailTracking (Account, ExpirationDate)" & _
"Values ('" & AccountName & "', '" & ExpirationDate & "')"
test.MoveNext
Loop
test.Close
rst.MoveFirst
Do Until rst.EOF
rst.Edit
rst!EmailSent = 1
rst.Update
rst.MoveNext
Loop
'DoCmd.Requery
rst.Close
DoCmd.RunMacro ("Close")
'DoCmd.OpenQuery ("qryDeleteEmail")
End If
Exit Sub
End Sub
What's happening right now is it's copying the first record of the staging table twice. For instance I have an account name A and an account name S, but instead of inserting the record for A and the record for S, it is simply inserting A twice.
Any help would be greatly appreciated!
Create and test a simpler procedure which is narrowly focused on the issue you're trying to solve. Unfortunately, I'm not sure what that issue is. I'll suggest this anyway ...
Public Sub TestLoopThruTable()
Dim db As DAO.database
Dim test As DAO.Recordset
Dim strInsert As String
DoCmd.SetWarnings True ' make sure SetWarnings is on
Set db = CurrentDb
Set test = db.OpenRecordset("tblEmailTemp")
Do While Not test.EOF
strInsert = "INSERT INTO EmailTracking (Account, ExpirationDate)" & vbCrLf & _
"VALUES ('" & AccountName & "', '" & ExpirationDate & "')"
Debug.Print strInsert
'db.Execute strInsert, dbFailOnError
test.MoveNext
Loop
test.Close
Set test = Nothing
Set db = Nothing
End Sub
Notice in your original version there was no space between ExpirationDate) and Values. I used a line break (vbCrLf) instead of a space, but either will keep the db engine happy.
I made sure SetWarnings is on. In your code, you turned it off at the start but never turned it back on again. Operating with SetWarnings off suppresses important information which you could otherwise use to understand problems with your code.
As that code loops through the recordset, it simply creates an INSERT statement and displays it for each row. You can view the output in the Immediate window (go there with the Ctrl+g keyboard shortcut). Copy one of those INSERT statements and test by pasting into SQL View of a new Access query. If it fails there, figure out what you need to change to satisfy the db engine. If the INSERT succeeds, try executing them from your code: enable the db.Execute line by removing the single quote from the start of that line.
The way you wrote the VALUES clause, it appears [ExpirationDate] is a text field. However if its data type is actually Date/Time, don't include quotes around the value you're inserting; use the # date delimiter instead of quotes.
Also make sure to include Option Explicit in the Declarations section of your code module like this:
Option Compare Database
Option Explicit
I mentioned that point because in an earlier version of this question you showed Option Compare but not Option Explicit. Trying to troubleshoot code without Option Explicit is a waste of time IMO.
I am not sure to understand what you are trying to do here; it is hard to understand what ErrorHandler is doing in the Else statement (even if commented).
As far as looping through a recordset goes, I advice you to read a little bit about the basis of VBA programmation in MS-Access. You can start by reading the articles below. It is a quick introduction about VBA recordsets and then the most common mistakes in VBA.
http://allenbrowne.com/ser-29.html
http://www.techrepublic.com/blog/10things/10-mistakes-to-avoid-when-using-vba-recordset-objects/373
It should help you improving your code.
In the comments on this answer, Remou writes that
CurrentDB.Execute "insert sql here"
is better than
DoCmd.SetWarnings = 0
DoCmd.RunSQL "insert sql here"
due to the built-in warnings that Access produces. I'm trying to understand the difference.
If they both mask errors, why is the first one preferable over the second? Are there any best practices here?
They do not both mask errors. DoCmd.SetWarnings masks errors and is system wide, not confined to the single application that you are using. DoCmd.SetWarnings False without the corresponding DoCmd.SetWarnings True will mean that action queries will run without any prompts in any Access application on the PC.
Execute does throw warnings, the warnings that you need, such as the query failed to execute, but does not give warnings you may not need, such as "Are you sure you want to run this query".
In this thread Allen Browne, Access MVP, says he does not use Set Warnings.
As an aside, I would generally recommend using an instance of CurrentDB, as this will allow you to return a record count, amongst other things, so:
Set db = CurrentDB
db.Execute sSQL, dbFailOnError
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