Hide Dialog box when running append query in VBA ODBC - ms-access

I want to run a saved access query through a button click using VBA. I don't want the user to be asked to confirm that it runs.
CODE:
DoCmd.OpenQuery "QryAddTraining", acViewNormal, acAdd
This brings up the dialogue box "You are about to run append query that will modify data in your table" ....
I just want the VBA code to automatically select "Yes" and stop the user from seeing this interface.

Use DAO.Database.Execute to execute your query:
Dim db As DAO.Database
Set db = CurrentDb
db.Execute "QryAddTraining", dbFailOnError
The dbFailOnError option is not required, but including it gives you better error information. Check the Access help topic for details.

Related

Records cannot be deleted with this form access error

I have made a search box in Access that will set the Access form's recordset to ADO recordset once the result is found.
The code is
rs.Open "select * from main where Name= '" & Me.txtSearch.Value & "';", CurrentProject.Connection, adOpenDynamic, adLockOptimistic
Set Me.Recordset = rs
This lets me find the records much faster than default Access ctrl+f method which is slower with linked tables.
However, it looks like I cannot delete the records that were found using the search field that I made.
If i try to delete it, I get:
Records cannot be deleted with this form access
at the bottom of the form.
Is there a way to have deletable ADO record bound to Access form?
The reason the ADO bound form was not editable is not because of cursor type or lock type but because of cursor location. Adding
rs.CursorLocation = adUseClient
did the job for me.
Also in this discussion thread Dirk Goldgar writes:
One possible consideration is that, if you're binding an Access form
to an ADO recordset, I've found that using a server-side cursor makes
the form read-only.
So far, I have not found any explanation on why this is the case. Please reply if anyone knows why server side cursor bound to Access form makes it uneditable.
EDIT 1:
Also Made Sure that you are using currentproject.connection and not an ADO connection string

Access VBA Requery not available now Error 2046

I am trying to refresh 2 queries,
MyTaskQuery and MyTaskActions
Both queries contain an INSERT SLQ statement to insert values from other tables in to table MyTasksTbl
The Query MyTaskQuery then selects the actions from MyTasksTbl that have my username.
When I've added the Delete SQL command (to remove any completed/closed actions and ensure there are no duplicates), I get a
Run-time error 2046, The command or action 'Requery' isn't available
now.
Can anyone advise me why I am getting this error? The code runs on form_load()
SQL = "Delete * From MyTasks Where UserName = '" & User & "';"
DoCmd.RunSQL SQL
DoCmd.Requery MyTaskQuery
DoCmd.OpenQuery MyTasksActions
You can only requery open objects. You can get this error when trying to requery a closed object.
You can test if a query is opened before requerying with the following code:
'Since you aren't using apostrophes, I assume the query name is stored in a variable
If CurrentData.AllQueries(MyTaskQuery).IsLoaded Then
DoCmd.Requery MyTaskQuery
End If
Note that opening an object just to requery it is pointless, since it already requeries when opened.

How to force an Access query datasheet to refresh its data

I am new on access and what I am trying to do is a select with a criteria so I created a query with the wizard and seted the criteria with a text from a form ([Forms]![Form1]![Transacao]) and created a button to run the query at the first time works great but when I type something else and click the button the datas do not refresh. What I have to do to refresh? I've tryed to add refresh on the event click of the button and did not work.
Thanks in advance for your help.
In Access, a query is usually opened in a default Datasheet view. This default datasheet is contained in a window (or tab) that is only accessible using Macros or DoCmd in VBA.
Once a query window is open, its data will not necessarily update automatically when new records are added to the underlying table(s). The datasheet needs to be "requeried". (Incidentally, the term "refresh" is usually reserved to mean "redrawing" a window on the screen and has nothing to do with the data. This is especially the case in programming and development environments which deal with data and drawing/painting windows and controls on the screen.)
Here is one way to force a query to update its data (when open in its default datasheet view):
DoCmd.OpenQuery "QueryName"
DoCmd.Requery
Calling OpenQuery should also activate the query window if it is already open. If you find that the windows does not activate, you can also call DoCmd.SelectObject acQuery, "QueryName" before DoCmd.Requery.
The DoCmd methods correspond to Macro actions, so if the query is activated by a Macro, just add the Requery action to the macro after the OpenQuery or SelectObject actions. Leave the Control Name parameter of the Requery action blank to force the entire query to updated.
I know this question is a bit stale at this point, but since I couldn't find a suitable answer to this question and the above answer didn't work for me (and still hasn't been accepted), I thought I'd offer my solution for those few poor saps still stuck developing applications in Access. My use case was slightly different (changing the underlying SQL of a query, then opening/refreshing it), but the same principle could be applied. The gist is to first check to see if the query is open and close it if it is. Then open it up again.
To do this, paste this code into a VBA module:
Public Function open_or_refresh_query(query_name As String, Optional sql_str As String = "")
' Refresh or open an existing query
' query_name: Name of the query
' sql_str: optional new SQL string if changing the underlying SQL. If not given,
' the query will open with its existing SQL string
On Error GoTo err_handler
Dim qdf As QueryDef
' Loop through each query in the DB and find the one of interest by name
For Each qdf In CurrentDb.QueryDefs
If qdf.Name = query_name Then
' If the query is open, close it
If SysCmd(acSysCmdGetObjectState, acQuery, query_name) <> 0 Then
DoCmd.Close acQuery, query_name, acSaveNo
End If
Exit For
End If
Next qdf
Set qdf = CurrentDb.QueryDefs(query_name)
' Reset the SQL if new SQL string was given
If Len(sql_str) > 0 Then qdf.sql = sql_str
' Close the QueryDef object to release resources
qdf.Close
' Open the query in default datasheet view
DoCmd.OpenQuery query_name
exit_function:
Exit Function
err_handler:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Error"
Resume exit_function
End Function
At this point you could call this function from any other VBA code in your project. To open/refresh a query from a macro as the OP wanted to do, create a new macro and add a RunCode action with open_or_refresh_query("my_query") in the Function Name field, changing my_query to the name of your query.

Editing a query in another DB

Is it possible to open a second Access database from within an Access database, and edit a query in that second DB? I know you can open one Access DB from another, but I'm just not sure whether or not you can edit a query that way.
If it's possible, can anyone show me some sample code to do this?
Use OpenDatabase to return a DAO.Database reference to your remote database. Then you can access a saved query via its QueryDefs collection.
Here is an example from the Immediate window:
set db = OpenDatabase("C:\share\Access\Database1.mdb")
Debug.Print db.QueryDefs("Query1").SQL
SELECT dbo_foo.bar, TypeName(bar) AS TypeOfBar
FROM dbo_foo;
db.QueryDefs("Query1").SQL = "SELECT d.bar, TypeName(d.bar) AS TypeOfBar" & vbcrlf & _
"FROM dbo_foo AS d;"
Debug.Print db.QueryDefs("Query1").SQL
SELECT d.bar, TypeName(d.bar) AS TypeOfBar
FROM dbo_foo AS d;
db.close

Access the database engine could not lock table - Make Table script for fields held on the form

I'm having a bit of trouble with some vba script i'm attempting to run from a button on a form.
Via a linked MDB file, I've written a string of Make Table queries that help certain other queries work. Rather than have the user re-run each individual Make Table query one-by-one, I've put the queries in a VBA script (using DoCmd.RunSQL) and then assigned that script to a button on a form.
The data source i'm using also has a File Info table that contains the File Name and the File Date of the data.
When the user clicks the button, I'd like them to know what data source was used when the string of Make Tables queries was run; that way they know what data the script was run on.
My approach to this was to create a final Make Table query using the File Info table to put the File Name and File Date in it's own table.
I would then add these fields to the form and add the DoCmd.RunSQL for this final Make Table query in to the bottom of the VBA script for the button; once all the Make Tables had run, the File Info and File Date fields would then be displayed/updated on the form telling the user what data file had been used the last time the script was run.
Here's the code for this (for brevity I've summarised all the Make Table scripts that run prior to the FileInfo as some bogus "AllOtherMakeTables" string)
Private Sub Command0_Click()
On Error GoTo Err_Command0_Click
DoCmd.SetWarnings False
Dim AllOtherMakeTables As String
Dim FileInfoStamp As String
AllOtherMakeTables = " SELECT SomeField INTO AnotherTable" _
& " FROM SomeTable" _
FileInfoStamp = " SELECT FileInfo.FileName, FileInfo.FileDate INTO FileInfoStamp" _
& " FROM FileInfo;" _
DoCmd.RunSQL AllOtherMakeTables
DoCmd.RunSQL FileInfoStamp
DoCmd.SetWarnings True
Exit_Command0_Click:
Exit Sub
Err_Command0_Click:
MsgBox Err.Description
Resume Exit_Command0_Click
End Sub
Clicking the button using the script above yields the following error message:
The database engine could not lock table 'FileInfoStamp' because it is
already in use by another person or process
I think what is happening is the fields I added to the form (FileName and FileDate) are locking the FileInfoStamp table when the form is open, so when the script tries to recreate the FileInfoStamp it is unable to do this as the table is locked.
I thought this might be fixed simply by adding a DoCmd.Close at the start of the above script and then adding a DoCmd.OpenForm at the end of the script (essentially closing the form whilst the Make Table commands are run and then re-opening the form at the end).
All this does though is close the form and bring up the same error message. So I guess even though the form is "closed" the connections with the fields on the form still remain active in some way(...?)
Any assistance on how I might get around this would be much appreciated. Thank you.
Do not recreate FileInfoStamp each time. Use these two steps instead:
discard existing rows
append the new data
Dim db As DAO.database
Dim FileInfoStamp As String
FileInfoStamp = "INSERT INTO FileInfoStamp(FileName, FileDate)" & vbCrLf & _
"SELECT fi.FileName, fi.FileDate FROM FileInfo AS fi;"
Debug.Print FileInfoStamp
Set db = CurrentDb
' empty out FileInfoStamp
db.Execute "DELETE FROM FileInfoStamp;", dbFailOnError
' add new data to FileInfoStamp
db.Execute FileInfoStamp, dbFailOnError
Set db = Nothing
Add an error handler to deal with any problems turned up from dbFailOnError.
Instead of DoCmd.RunSQL, use the DAO database .Execute method for your other queries. With that approach, you will not have any motivation to use DoCmd.SetWarnings False. Turning SetWarnings off is unwise because it suppresses information you need to diagnose problems.