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.
Related
I'm trying to figure out if/how I can generate a new query window in the Design View either via a macro or VBA code.
Specifically, I want to open a new, blank query in SQL View so I can quickly test SQL code. This is a common activity for me.
I usually create a new query manually via the Ribbon: Create tab > Query Design button > Close (Show Table window) button > SQL View button. This results in a new window called Query1 (or Query2, etc.).
I'd like to condense all of those multiple clicks into a keyboard shortcut or a single macro button on the Quick Access Toolbar. Note that I'm using Access 2010.
Possible?
Add this to a module:
Function NewQueryInSqlView()
' Send the ESC key, without waiting for processing,
' to cancel the select table dialog that occurs when designing new query
SendKeys "{ESC}", False
DoCmd.RunCommand acCmdNewObjectDesignQuery ' create new query
DoCmd.RunCommand acCmdSQLView ' switch to SQL view
End Function
To execute the code by way of a keyboard shortcut, create a new macro, and ensure "Macro Names" column is visible.
Add the following row to macro with the following values in the specified columns:
Macro Name: +{F3}
Action: RunCode
with Function Name argument: NewQueryInSqlView()
Save this macro as "AutoKeys". This macro will map SHIFTF3 to the execution of NewQueryInSqlView(). Note that choosing a key mapping starting with CTRL (the ^ character) will be problematic due to the SendKeys statement in NewQueryInSqlView().
Write a function and call it from a macro:
Public Function foo()
Dim qdf As QueryDef
Set qdf = CurrentDb.CreateQueryDef("qNew", "SELECT 'd' as foo")
DoCmd.OpenQuery qdf.Name
End Function
This will create the query and open it
The macro is a RunCode command that runs the above function.
Try This code:
Sub EmptyQuery()
Dim Qname As String
Qname = "mQname"
On Error Resume Next
CurrentDb.CreateQueryDef Qname
On Error GoTo 0
DoCmd.OpenQuery Qname, acViewDesign
End Sub
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.
I have a very complex process that involves downloading a number of files from different shares, concatenating those files into working tables, manipulating and calculating related information, and then exporting specific fields (and calculations) as reports into a number of Excel workbooks.
I have this process coded so that I can click one button and the entire process will execute end to end. I have a series of text boxes that function as 'indicators' (red - this part failed, green - this part succeeded). As you can imagine, the code for the entire process is HUGE (32 pages when copied into MSWord) and difficult to weed through when I have a problem.
I got it into my mind that I wanted to put the code into a table so that it was much more modular and easier to deal with. I have setup a combo box with the action that I want to take and a second combo box with the report/file/object that I want to work with (ie Delete - Table 2, Acquire - File 1, Export - Report 4). I have been successful at creating the SQL statement to do simple things like del * from tbl_test and execute that from the combo boxes without any issue.
What I need to know is if there is a way to put what is essentially a code snippet into the table (memo field) and then have that vba code execute when I select the matching combos.
IE the code for 'Acquire - File1' is completely VBA code; it maps a network drive, locates the file, downloads the file, and moves it to a directory.
IE the code for 'Scrub - tblMain_Part1' is a combination of vba and sql code; it checks for the existence of a file (vba), if it finds it, it deletes a portion of the main table (sql) and appends the contents of the file it finds (sql), then it updates the monitor to indicate that it is completed (vba). If the file is not found, it changes the monitor box to red and updates a command button caption (vba)
I am NOT a genius with vba, but I hold my own. The thought process I had was that if I can essentially get the code broken into managable chunks in the table, I could call the code smippets in order if I want to run the entire process, or I could just re-execute portions of the code as needed by selecting the action and report/file/object combination.
Any thoughts/ideas are appreciated.
I think it would be best to split the code into Subs. The table you loop through would have a Sub-Name field and a blnSuccess field. Your code would loop though the table running each sub and then updating blnSuccess based on any errors you receive. This would give you queryable result set when you try to see what happened.
Consider using macros. You shouldn't need a table. Also, consider moving your hard-coded SQL to queries.
I think that you shouldn't use a table, just create a module with different subs for each operation. On your button event, after the combo selections, I would do a case statement.
dim strOperation as string
strOperation = me!selectionOne
Select Case strOperation
Case "delete": deleteTable(me!selectionTwo)
Case "export": export(me!selectionTwo)
case "acquire": acquire(me!selectionTwo)
End Select
Of course, you'd have your acquire, delete, and export methods written in a module and have whatever parameters you need for each operation there.
This is just one idea of many that you could use to approach this.
I was going to edit the original answer but this seems to be off on a different tack....
I think it would be best to split the code into functions that return a string if there is an error. The table you loop through would have a strFunction,strError and strObject fields. Your code would loop though the table running each function based on the case statement while passing the strObject as a string and then updating strError based on any errors you receive. You could query the table after this process to see which records have errors in them.
If the button is called cmdRunAll here is the code for it.
Private Sub cmdRunAll_Click()
On Error GoTo ErrHandler
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("tblCode", dbOpenDynaset, dbSeeChanges)
If Not rst.EOF Then
With rst
.MoveFirst
Do While Not .EOF
.Edit
Select Case !strFunction
Case "fExport"
!strError = fExport(!strObject)
End Select
.Update
.MoveNext
Loop
End With
End If
rst.Close
Set rst = Nothing
MsgBox "Processes complete"
Exit Sub
ErrHandler:
Debug.Print Err.Description & " cmdRunAll_Click " & Me.Name
Resume Next
End Sub
Here is a simple sample function
Public Function fExport(strTable As String) As String
On Error GoTo ErrHandler
Dim strError As String
strError = ""
DoCmd.TransferText acExportDelim, , strTable, "C:\users\IusedMyUserNameHere\" & strTable & ".txt"
fExport = strError
Exit Function
ErrHandler:
strError = Err.Description
Resume Next
End Function
i am trying to create a Report based on a query which will be made on each
creation / update of my DataBase
i attach the report to a button with a macro,
problem is that if nothing was changed and someone just press over the button the report would be fired but with no data, and if the data was inserted to the text boxes and i press over the button with the macro the data does not append to the data base.
my macro lines:
OnError Next,
OpenReport Accept, Report, , , Normal // Accept is the name of the report
GoToRecord Next,
[MacroError]<>0 =[MacroError].[Description], Yes, None,
Thanks in advance for your help
A good way to test and track this would be by adding a 'Yes/No' field called for example "flgReported" in to one of the tables used in the query, then after running your report you could update all rows to true. Any new rows added afterwards would then be false and you could bring this in to your select query to only report on False rows, this would also allow you to test whether there was any data to return when clicking the button before going ahead and running the report.
Update: If you highlight the macro in question and then goto "Tools > Macro > Convert Macro's to Visual Basic" and then click 'Convert' it will generate the VB code for you. This could then be called from your button instead of the Macro and before the main procedure you could insert this to check if there were any new records:
Private Sub ButtonClick() "For Example"
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM queryname where flgReported = False")
If rs.BOF And rs.EOF then 'No Records to report so we quit at this point
rs.close
set rs = Nothing
Exit Sub
End If
'Remainder of Macro Code goes here
'Then run a simple SQL here to update the flags to True
End Sub
There is some literature available at expert's exchange and at teck republic about using the combobox.recordset property to populate a combobox in an Access form.
These controls are usually populated with a "SELECT *" string in the 'rowsource' properties of the control, referencing a table or query available on the client's side of the app. When I need to display server's side data in a combobox, I create a temporary local table and import requested records. This is time consuming, specially with large tables.
Being able to use a recordset to populate a combobox control would allow the user to directly display data from the server's side.
Inspired by the 2 previous examples, I wrote some code as follow:
Dim rsPersonne as ADODB.recordset
Set rsPersonne = New ADODB.Recordset
Set rsPersonne.ActiveConnection = connexionActive
rsPersonne.CursorType = adOpenDynamic
rsPersonne.LockType = adLockPessimistic
rsPersonne.CursorLocation = adUseClient
rsPersonne.Open "SELECT id_Personne, nomPersonne FROM Tbl_Personne"
fc().Controls("id_Personne").Recordset = rsPersonne
Where:
connexionActive: is my permanent ADO connection to my database server
fc(): is my current/active form
controls("id_Personne"): is the
combobox control to populate with
company's staff list
Access version in 2003
Unfortunately, it doesn't work!
In debug mode, I am able to check that the recordset is properly created, with requested columns and data, and properly associated to the combobox control. Unfortunately, when I display the form, I keep getting an empty combobox, with no records in it! Any help is highly appreciated.
EDIT:
This recordset property is indeed available for the specific combobox object, not for the standard control object, and I was very surprised to discover it a few days ago.
I have already tried to use combobox's callback function, or to populate a list with the "addItem" method of the combobox,. All of these are time consuming.
To set a control that accepts a rowsource to a recordset you do the following:
Set recordset = currentDb.OpenRecordset("SELECT * FROM TABLE", dbOpenSnapshot)
Set control.recordset = recordset
Works with DAO Recordsets for sure, I haven't tried ADO recordsets because I don't have any real reason to use them.
When done this way, a simple requery will not work to refresh the data, you must do a repeat of the set statement.
As was said, you have to get the RowSourceType to "Table/Query" (or "Table/RequĂȘte" if in french) in order to show query results in the combobox.
Your memory problems arise from opening the recordset (rsPersonne) without closing it. You should close them when closing/unloading the form (but then again you would have scope problems since the recordset is declared in the function and not in the form).
You could also try to create and save a query with Access's built-in query creator and plug that same query in the RowSource of your combobox. That way the query is validated and compiled within Access.
I found the trick ... the "rowSourceType" property of the combobox control has to be set to "Table/Query". Display is now ok, but I have now another issue with memory. Since I use these ADO recordsets on my forms, memory usage of Access is increasing each time I browse a form. Memory is not freed either by stopping the browsing or closing the form, making MS Access unstable and regularly freezing. I will open a question if I cannot solve this issue
good method with using the Recordset property, thanks for that hint!
Patrick, the method you shown on your page has a big disadvantage (I tried that too on my own): The value list can only be 32 KB, if you exceed this limit the function will throw an error.
The callback method has the big disadvantage that it is very slow and it is called once for every entry which makes it unuseable for a longer list.
Using the recordset method works very well. I needed this because my SQL string was longer than 32 KB (lot of index values for WHERE ID IN(x,x,x,x,x...)).
Here's a simple function which uses this idea to set a recordset to the combobox:
' Fills a combobox with the result of a recordset.
'
' Works with any length of recordset results (up to 10000 in ADP)
' Useful if strSQL is longer than 32767 characters
'
' Author: Christian Coppes
' Date: 16.09.2009
'
Public Sub fnADOComboboxSetRS(cmb As ComboBox, strSQL As String)
Dim rs As ADODB.Recordset
Dim lngCount As Long
On Error GoTo fnADOComboboxSetRS_Error
Set rs = fnADOSelectCommon(strSQL, adLockReadOnly, adOpenForwardOnly)
If Not rs Is Nothing Then
If Not (rs.EOF And rs.BOF) Then
Set cmb.Recordset = rs
' enforces the combobox to load completely
lngCount = cmb.ListCount
End If
End If
fnADOComboboxSetRS_Exit:
If Not rs Is Nothing Then
If rs.State = adStateOpen Then rs.Close
Set rs = Nothing
End If
Exit Sub
fnADOComboboxSetRS_Error:
Select Case Err
Case Else
fnErr "modODBC->fnADOComboboxSetRS", True
Resume fnADOComboboxSetRS_Exit
End Select
End Sub
(The function fnADOSelectCommon opens an ADO recordset and gives it back. The function fnErr shows a message box with the error, if there was one.)
As this function closes the opened recordset there should be no problem with the memory. I tested it and didn't saw any increasing of memory which wasn't released after closing the form with the comboboxes.
In the Unload Event of the form you can additionaly use a "Set rs=Me.Comboboxname.Recordset" and then close it. This should not be necessary regarding memory, but it may be better to free up open connections (if used with a backend database server).
Cheers,
Christian
A combo box control does not have a recordset property. It does have a RowSource property but Access is expecting a SQL string in there.
You can change the RowSourceType to the name of a user defined "callback" function. Access help will give you more information including sample code by positioning yourself on the RowSourceType and pressing F1. I use this type of function when I want to give the users a list of available reports, drive letters, or other data that is not available via a SQL query.
I don't understand what you mean by your third paragraph with respect to using data directly from the server side. Or rather I don't understand what the problem is with using standard queries.
In MS Access, it's ok, but in VB, you may use something like this using adodc (Jet 4.0):
Private sub Form1_Load()
with Adodc1
.commandtype = adcmdtext
.recordsource = "Select * from courses"
.refresh
while not .recordset.eof
combo1.additem = .recordset.coursecode
.recordset.movenext
wend
end with
End Sub