Hey subform - let go of my Table - vba

I'm having a bit of an issue with timing, I think, that's driving me batty!
I have a Form with a subform with a Table as recordsource (as a datasheet)
Users can edit the data in the datasheet
Upon closing the form (via btnSave), I intend to run a function that exports the datasheet, with its changes to an XLS via Transfer spreadsheet.
Access is complaining the table is "already in use"
I have attempted to set the subform's recordsource = "" then requery
Same complaint from Access about the table - but table is not open!
Any suggestions how and where to attach the export function?
Note: The export function works just fine under its own dedicated button on the MainForm. I just want to run this same function when I close the form/subform.

HansUp, I can confirm the following syntax also works:
Forms![Matched]![Matched subform].SourceObject = ""
Thanks for the suggestion!

Crude, but effective:
DoCmd.Close acForm, "Forms![Matched]![Matched subform]", acSaveNo
No more complaints about the locked table
HansUp, I'll play with that syntax; always fuzzy trial and error on those pesky sufbform properties.

Related

Save query using VBA

I have form with multiple textboxes that are used to filter Subforms. The Subform Source Objects are queries. In order to filter the Subforms I update the query SQL and reassign the query as the source object on the subform.
Set qdf = db.QueryDefs("MyQuery")
qdf.SQL = strNewSQL
mySubForm.SourceObject = "Query.MyQuery"
The filtering works correctly. However when I close my form, I get a message asking if I want to save changes to the queries. How can I avoid this message?
Edit:- Following comment by #June7, closing form using
DoCmd.Close acForm, "MyForm", acSaveNo
solved my issue.
It is also possible to close the form using an embedded macro and setting prompt = No.
Using VBA instead of embedded macro solved your issue but consider that code can be simplified to:
CurrentDb.QueryDefs("MyQuery").SQL = strNewSQL
Me.mySubForm.SourceObject = "Query.MyQuery"

Access VBA unable to refresh a form

I have a form (frmDropDownEdit) that has a filtered table as the data. A "New" button is created that opens another form (frmDropDownNew) and the user can enter new data. When complete the new form is closed and the user is back to the original form. The code for frmDropDownNew correctly add the info to the table, then the code refreshes the frmDropDownEdit form but it does not refresh. If I click the refresh button in the ribbon, it also does not refresh. But refresh all does work.
How can I have my code refresh the data in frmDropDownEdit. I also put code me.refresh on the OnGotFocus event but that does not even run.
Here is my source code
Private Sub Command5_Click()
'Add Button
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("tblDropDown")
rst.AddNew
rst!DdCategory = Me.txtCategory.Value
rst!DdDescription = UCase(Me.txtDescription.Value)
rst.Update
rst.Close
DoCmd.Close
Forms!frmDropDownEdit.Refresh
End Sub
On my MS Access 2010 ×64 single user PC, Forms![AnyForm] .Refresh never worked in VBA, independently where it is placed in any database's code. Form_Current() doesn't run either as it should after data are modified (verified by putting a Stop therein). Moreover, records with modified data are neither marked dirty nor refreshed before the vba code has finished. Procedures which should run without delay when data are modified don't run, even when placed into the modified fields' events.
Thus, one has to use a work-around. Many people recommend to use .Requery instead of .Refresh and then to return by vba code to the desired record, but this requires a field with a primary key.
My solution for tables without primary key is the following:
'…
' ESSENTIAL: this code must be run from ANOTHER module !
' (it runs without error in MyForm's own code [eg. in Form_Activate(),
' but then MyForm is NOT immediately refreshed as desired,)
' one still has to repeat these steps by hand afterwards…
DoCmd.GoToRecord acForm, "MyForm", acNext
DoCmd.GoToRecord acForm, "MyForm", acPrevious
' NB: Forms![MyForm].Refresh doesn't work
' at this place in "MyOtherModule" either.
'…
As mentioned in above code comments: this code must be run from another module ("MyOtherModule") - in my case, a form-independent procedure called upon closing a pop-up form opened from the first form, which interactively modifies data. These data should be updated/refreshed immediately when closing the pop-up form, reflecting all changes and their consequences (for example, automatic filling-in/deleting of other data and/or en/disabling controls or making them [in]visible, depending on the modified fields' values).

How to disable the "Select Data source window in VBA"

I have a excel file with macro-enabled that is used to upload the data from excel into a database. There's a button in excel to run this code. When I run the code, it has a window pop-up "Select Data Source". Does anyone how to prevent this from popping up.
Thank You
Sadly as a beginner I cannot provide the picture so I will explain.
When the button is clicked. A window is opened named "Select Data Source" with three options dBASE Files, Excel Files, MS Access Database. I need to select one of them and continue on. For me it's excel so I click this and press okay. Then it has the option of allowing me to select the workbook. Is there a way to pre-do this before so that I don't see this window.
The code is shown Below, which gives this problem.
Sub Collect_campaigns()
Dim qryCampaigns As String
Application.ScreenUpdating = False
qryCampaigns = "SELECT * FROM test.tbl_test;"
Worksheets("Campaigns").Visible = True
Sheets("Campaigns").Select
Range("A:F").Select
Selection.Clear
Range("A1").Select
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=TEST_DATASOURCE;", Destination:=Range("$A$1")).QueryTable
.CommandText = qryCampaigns
.Refresh BackgroundQuery:=False
End With
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=TEST_DATASOURCE;", Destination:=Range("$A$1")).QueryTable
As you can see in the code above, your macro refers to ODBC DataSource named TEST_DATASOURCE. I can only assume that you have copied this file from other computer, if so you also need to create same ODBC Datasource on your machine too.
If your machine is running Windows you should check "Control Panel-->Administrative Tools-->Data Sources(ODBC)".
The pop-up window is a polite way of telling you that it cannot reconcile your datasource "ODBC;DSN=TEST_DATASOURCE;" with the available ODBC data sources. Your minimialistic approach is a good one, I think -- not putting the entire connection string in but just the name. It allows MS Query to fill in the blanks based on your ODBC connection settings).
Although less likely, it could also have something to do with the password, where the ODBC connection is rejecting the attempted use at the embedded password. Since you said your data source is Excel, I'm going to put that into the 'unlikely' category... unless your data source isn't really Excel and you were pulling our proverbial legs.
My recommendation would be to apply good programming practices: cheat and be lazy
Record macro
Create the table as you would normally in Excel, Data->From Other Sources->MS Query (or whatever)
Stop the macro
Now run the macro code on a clean workbook -- with any luck it will run fine. Then, strip out pieces of fluff code as you see fit and continue to re-test it until it breaks.

MS-Access 2003 trigger an append query from a command button click

I have an append query that I would like to trigger off of a command button click. I have my splash screen with a command button that executes a Close & Open command. I want to combind the append query to execute during this click event.
My VBA for the splash screen
Option Compare Database
Private Sub SplCls_Click()
On Error GoTo Err_SplCls_Click
DoCmd.Close
stDocName = "Switchboard"
DoCmd.OpenForm stDocName
Exit_SplCls_Click:
Exit Sub
Err_SplCls_Click:
MsgBox Err.Description
Resume Exit_SplCls_Click
End Sub
I know enoug to know it needs to go in between the DoCmd.Close & DoCmd.OpenForm. The Append query is named "qry_YOS" Any guidance on this segment of code would be greatly appreciated.
Use the DAO Database Excute method to run your append query. If you want that to happen between .Close and .OpenForm ...
DoCmd.Close ' close what? If it works, fine. '
CurrentDb.Execute "qry_YOS", dbFailonerror
stDocName = "Switchboard"
DoCmd.OpenForm stDocName
BTW, always include Option Explict in the Declarations of your code modules like this:
Option Compare Database
Option Explicit
From the VB Editor's main menu, select Tools->Options. Then on the Editor tab of the Options dialog, place a check mark next to "Require Variable Declaration". That setting will ensure Option Explict is included in all new code modules. I strongly recommend you manually add it to any of your existing code modules which don't already have it. Then choose Debug->Compile from the VB Editor's main menu and fix anything the compiler complains about. Hopefully that won't be too much, but in the long run it's a good investment.
Life as a VBA developer without Option Explicit is unnecessarily complicated. Just always use it to save yourself grief. You can thank me later. :-)

Requery a subform from another form?

I've struggling with this problem on my own, then with some help, then search about it; but I haven't had any luck. So I decided to ask.
I have two forms in Access 2007 lets call them MainForm and EntryForm.
MainForm has a subform and a button. The button opens the EntryForm in Add Mode. What I want to do is when the EntryForm saves the new record it would update (requery) the subform in MainForm.
I've try this setup code
Private Sub cmdSaveAndClose_Click()
DoCmd.Save
'requery list
Forms![MainForm]![subformName].Requery
'' I've also tried these
'Forms![MainForm]![subformName].Form.Requery
'Forms.("MainForm").[subformName].Requery
'Forms.("MainForm").[subformName].Form.Requery
DoCmd.Close
End Sub
None of these attempts seem to work. Is there a way to make this requery?
Thanks for the help in advance.
You must use the name of the subform control, not the name of the subform, though these are often the same:
Forms![MainForm]![subform control name Name].Form.Requery
Or, if you are on the main form:
Me.[subform control name Name].Form.Requery
More Info: http://www.mvps.org/access/forms/frm0031.htm
Just a comment on the method of accomplishing this:
You're making your EntryForm permanently tied to the form you're calling it from. I think it's better to not have forms tied to context like that. I'd remove the requery from the Save/Close routine and instead open the EntryForm modally, using the acDialog switch:
DoCmd.OpenForm "EntryForm", , ,"[ID]=" & Me!SubForm.Form!ID, , acDialog
Me!SubForm.Form.Requery
That way, EntryForm is not tied down to use in one context. The alternative is to complicate EntryForm with something that is knowledgable of which form opened it and what needs to requeried. I think it's better to keep that kind of thing as close to the context in which it's used, and keep the called form's code as simple as possible.
Perhaps a principle here is that any time you are requerying a form using the Forms collection from another form, it's a good indication something's not right about your architecture -- that should happen seldom, in my opinion.
I tried several solutions above, but none solved my problem.
Solution to refresh a subform in a form after saving data to database:
Me.subformname.Requery
It worked fine for me. Good luck.
I had a similar kind of issue, but with some differences...
In my case, my main form has a Control (vendor) which value I used to update a Query in my DB, using the following code:
Sub Set_Qry_PedidosRealizadosImportados_frm(Vd As Long)
Dim temp_qry As DAO.QueryDef
'Procedimento para ajustar o codigo do cliente na Qry_Pedidos realizados e importados
'Procedure to adjust the code of the client on Qry_Pedidos realizados e importados
Set temp_qry = CurrentDb.QueryDefs("Qry_Pedidos realizados e importados")
temp_qry.SQL = "SELECT DISTINCT " & _
"[Qry_Pedidos distintos].[Codigo], " & _
"[Qry_Pedidos distintos].[Razao social], " & _
"COUNT([Qry_Pedidos distintos].[Pedido Avante]) As [Pedidos realizados], " & _
"SUM(IIf(NZ([Qry_Pedidos distintos].[Pedido Flexx], 0) > 1, 1, 0)) As [Pedidos Importados] " & _
"FROM [Qry_Pedidos distintos] " & _
"WHERE [Qry_Pedidos distintos].Vd = " & Vd & _
" Group BY " & _
"[Qry_Pedidos distintos].[Razao social], " & _
"[Qry_Pedidos distintos].[Codigo];"
End Sub
Since the beginning my subform record source was the query named "Qry_Pedidos realizados e importados".
But the only way I could update the subform data inside the main form context was to refresh the data source of the subform to it self, like posted bellow:
Private Sub cmb_vendedor_v1_Exit(Cancel As Integer)
'Codigo para atualizar o comando SQL da query
'Code to update the SQL statement of the query
Call Set_Qry_Pedidosrealizadosimportados_frm(Me.cmb_vendedor_v1.Value)
'Codigo para forçar o Access a aceitar o novo comando SQL
'Code to force de Access to accept the new sql statement
Me!Frm_Pedidos_realizados_importados.Form.RecordSource = "Qry_Pedidos realizados e importados"
End Sub
No refresh, recalc, requery, etc, was necessary after all...
By closing and opening, the main form usually runs all related queries (including the subform related ones). I had a similar problem and resolved it by adding the following to Save Command button on click event.
DoCmd.Close acForm, "formname", acSaveYes
DoCmd.OpenForm "formname"
Just discovered that if the source table for a subform is updated using adodb, it takes a while until the requery can find the updated information.
In my case, I was adding some records with 'dbconn.execute "sql" ' and wondered why the requery command in vba doesn't seem to work. When I was debugging, the requery worked. Added a 2-3 second wait in the code before requery just to test made a difference.
But changing to 'currentdb.execute "sql" ' fixed the problem immediately.
All your controls are belong to us!
Fionnuala answered this correctly but skimmers like me would find it easy to miss the point.
You don't refresh the subFORM you refresh the subform CONTROL. In fact, if you check with allforms() the subForm isn't even loaded as far as access is concerned.
On the main form look at the label the subform wizard provided or select the subform by clicking once or on the border around it and look at the "caption" in the "Other" tab in properties. That's the name you use for requerying, not the name of the form that appears in the navigation panel.
In my case I had a subform called frmInvProdSub and I tried for many hours to figure out why Access didn't think it existed. I gave up, deleted the form and re-created it. The very last step is telling it what you want to call the control so I called it frmInvProdSub and finished the wizard. Then I tried and voila, it worked!
When I looked at the form name in the navigation window I realized I'd forgotten to put "Sub" in the name! That's when it clicked. The CONTROL is called frmInvProdSub, not the form and using the control name works.
Of course if both names are identical then you didn't have this problem lol.
I ran into this issue today.
I was in a form that contained a button on subform1. Subform1 made changes to Subform2 that required a requery.
I found success with: Me.Parent.subform2.form.recordset.requery