Runtime query does not work.Why? - ms-access

I have a Problem with my codes and it made me confuse.this is my scenario:
in my access Project I have a Form and subform that work together.I wanted to enhace my performance . I deceided to load my form and subforms in Runtime(from this article) .I put my query on my form code, in Form_load event like this:
Private Sub Form_load()
Me.RecordSource = "SELECT DISTINCTROW tb_bauteile.* " & _
"FROM tb_bauteile LEFT JOIN FehlerCodes_akt_Liste ON tb_bauteile.CDT = FehlerCodes_akt_Liste.CDT " & _
"WHERE (((FehlerCodes_akt_Liste.Steuergerät)='MEDC17'))" & _
"ORDER BY FehlerCodes_akt_Liste.Fehlerpfad;"
End Sub
but another problem occured with another controls in my form.when i click another control .this function should be run:
Private Sub subPfadFilter(Kombifeld As Variant, Obd As String)
Dim strKrit, strAuswahl, strSg As String
If (IsNull(Me.CDT) Or (Me.CDT = "")) Then
strAuswahl = "*"
Else
strAuswahl = Me.CDT
blnFiltOn = True
End If
.....
but it doesn't work and say me method or dataobjectt not found( without this if statement works the function works fine .the problem come from CDT ) if I put the query in Datasource in my form property that works properly
I cant understand the relation between these two things(putting the query on datasource of form property then working the if statement (CDT) good but when i put the query in Form load that does not work ) ,would you please help me if posible?have you any idee?
thank you so much for your helps

When using the "Me" reference, you need to ensure the code is behind the present form, you've mentioned that the Form_Load code is on there, but is the "subPfadFilter" somewhere else?
If so then it needs to either be moved on to this form, or change your reference to the forms name instead of "Me".
If it is on the form then the error seems to be complaining about the CDT item, you will need to confirm that this is the name of either a text field or a control on this form.
If it is then you can try inserting:
Me.Requery
After your SQL statement, this may wake up the forms reference to the object.
This bit is not essential but to avoid carrying out two tests on CDT and streamlining your code slightly I would amend to this:
If Me.CDT & "" = "" Then
strAuswahl = "*"
Else
strAuswahl = Me.CDT
blnFiltOn = True
End If
This captures both Is Null or "" in one shot.
UPDATE:
For an unbound form, you need to set your form's controls via VB as well as the forms recordsource e.g:
Private Sub Form_load()
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("SELECT DISTINCTROW b.* " & _
"FROM tb_bauteile As b LEFT JOIN FehlerCodes_akt_Liste As f " & _
"ON b.CDT = f.CDT " & _
"WHERE f.Steuergerät = 'MEDC17' " & _
"ORDER BY f.Fehlerpfad;")
rs.MoveFirst
Me.CDT = rs!CDT
'Any other fields go here
rs.Close
Set rs = Nothing
End Sub
However if you are returning more than one record at a time then you will either need to stick with a bound form or perhaps use a listbox to display your information. Unbound forms do not use the Forms "Recordset" property.
Note: I have also 'Aliased' the table names in your SQL statement, this is a good practice to get into : )

Related

How to record unbound control to a database

I have a form control (address) that uses Dlookup to call info from a table "database" but the form is bound to table "Tracker". The dlookup is based on another control on the same form - "Name" I need the form to record this dlookup control, along with other controls that are bound to "tracker" as new recordto the table "tracker."
My failed attempts:
Using the default value property to assign the recalled data from the dlookup to another text box which would be bound to "tracker" This simply does not work for some reason. Perhaps I am missing something that tells this control "Address" to update upon selecting the correct "name?"
Code:
Private Sub SubmitReferral_Click()
On Error GoTo Err_SubmitReferral_Click
DoCmd.GoToRecord , , acNewRec
Exit_SubmitReferral_Click:
Exit Sub
Err_SubmitReferral_Click:
MsgBox Err.Description
Resume Exit_SubmitReferral_Click
End Sub
I also tried this - to assign the data - but the data from the dlookup in control "Address1" is not transferring/copying to control "Address2"
Private Sub Combo276_OnUpdate()
OnUpdate ([Address2].Value = [Address1].Value)
End Sub
Help or suggestions?
PS - I have tried to Edit per request to be as specific as possible, and to follow proper board etiquette.
Still unsure of your field names, etc., but the following is an example you can modify. Change 'tblEmployee' to 'database'.
I must state that if you are just starting out with developing in Access (or VBA) that you should never use names that are reserved words, or that can be misleading. Your table named 'database' is ok if named 'tblDatabase'.
Option Compare Database
option Explicit
Private Sub cmdInsert_Click()
Dim strSQL As String
Dim i As Integer
Debug.Print "cmdInsert; "
i = MsgBox("Do you want to add 1 row for Employee ID: " & Me.EmpID & " to table 'tracker'?", vbYesNo, "Confirm Add")
If i = vbNo Then
Exit Sub
End If
DoCmd.SetWarnings True
strSQL = "INSERT INTO tracker ( FirstName, LastName, Add1, City, St, Zip ) " & _
"SELECT tblEmployee.FirstName, tblEmployee.LastName, tblEmployee.Add1, tblEmployee.City, tblEmployee.St, tblEmployee.Zip " & _
"FROM tblEmployee " & _
"WHERE (((tblEmployee.EmpID)=" & Me.EmpID & "));"
DoCmd.RunSQL strSQL
End Sub
Thanks for the help - I solved my concern by hiding the fields that contain the dlookup, and putting code behind a button that copies the information to fields that are bound and therefore will record to the table "tracker"

Repopulating subform Recordset prompts for query parameters

I have a Continuous subform that filters data based on a series of queries. I then need to populate a subform that I have placed in the footer based on some data, and I have crafted a query to accomplish this.
Private Sub UpdateXXXXX_Info()
If (Me.FormFooter.Visible <> True) Then
Me.FormFooter.Visible = True
End If
MsgBox "query start"
LabelXXXXX_.Caption = "XXXXX for: " & Me.[XXXXX__NAME] & " " & Me.[XXXXX__NAME] & " " & Me.[XXXXX__CATEGORY_NAME]
With CurrentDb.QueryDefs("XXXXX_Query")
.Parameters("XXXXXParam") = Me.[XXXXX_NAME]
.Parameters("XXXXXCategoryParam") = Me.[XXXXX_CATEGORY_NAME]
Set Me.XXXXX__Subform.Form.Recordset = .OpenRecordset
.Close
MsgBox "query complete"
End With
End Sub
Which gets called from Click events tied to each of the controls on the continuous form. This works great, and filters as I expect.
Due to the nature of the continuous form (which itself is a subform of another form), the entire continuous form may need to be refreshed:
Private Sub Form_Current()
Me.FormFooter.Visible = False
End Sub
Which is causing an issue when refreshing the data. It works as-expected the first time around, however clicking on another record in the top continuous form causes the subform to prompt for query parameters. Based on testing, it is doing this when setting Me.FormFooter.Visible = True; although not setting Visible = False in the Current event circumvents this (which produces other, undesirable behavior).
Access will not let me .Close the Recordset, or otherwise set it to a blank or null value. I also cannot find any way to set the parameters for a Requery. The amount of data being presented also prohibits me from pulling the full table and applying a filter instead.
How can I prevent this behavior?
Edit: For clarification, I must use stored queries as a business requirement.
Use an SQL statement to (re)create the recordsource of the subform instead.
SQL = "SELECT * FROM xQuery WHERE xParam = '" & me!Name & "'" AND " & _
"xCategoryParam = '" & me!CategoryName & """
me!subform.form.recordsource = SQL
This eliminates any requirements to open/close the recordset, and avoids having to change your original query definition. (i.e. create your parameterless query, and the WHERE command in the SQL does the heavy lifting for you.
Aha!
geeFlo's answer pointed me to the RecordSource property of the form. Playing around with that, I was able to come up with the following:
Private Sub ClearXXXXXInfo()
If Me.FormFooter.Visible = True Then
Me.XXXXX_Subform.Form.RecordSource = ""
Me.FormFooter.Visible = False
End If
End Sub
Private Sub Form_Current()
ClearXXXXXInfo
End Sub

Passing query result to a textbox control on an access form

I need help with a textbox field on an Access 2007 form. I'm trying to insert the result of a query into the text box control on the form. This is used soley as information for the user. The form supplies the query with parameters to get the value. The query works fine and returns the correct result. What I can't seem to figure out is how to pass the query result to the textbox. I’ve tried several different ways but with no luck.
(PS> I know a combo box can do a lookup, however I don’t want the user to have to click the dropdown just to select the value as there can only ever be one value result from the query.) I'm open to suggestions as I'm not a programmer or DB Admin, but I've taking a few classes on Access (enough to be dangerous).
Private Sub cbo3_Change()
Me.tbx2 = ("SELECT tbl_Billing.Savings_b FROM tbl_Billing GROUP BY tbl_Billing.UBI_b, tbl_Billing.TaxYr_b, tbl_Billing.TaxPrg_b, tbl_Billing.Savings_b HAVING (((tbl_Billing.UBI_b)=forms!f1_UpBilled!cbo1) And ((tbl_Billing.TaxYr_b)=forms!f1_Upbilled!cbo2) And ((tbl_Billing.TaxPrg_b)=forms!f1_UpBilled!cbo3));")
End Sub
If you wish to do this in run time, you need to do the following, I take the controls you are referring to in this is on the same form.
The very simple and straight forward way to get it done is as follows,
Private Sub cbo3_Change()
Dim tmpRS As DAO.Recordset
Set tmpRS = CurrentDb.OpenRecordset("SELECT tbl_Billing.Savings_b FROM tbl_Billing GROUP BY " & _
"tbl_Billing.UBI_b, tbl_Billing.TaxYr_b, tbl_Billing.TaxPrg_b, " & _
"tbl_Billing.Savings_b HAVING ((tbl_Billing.UBI_b = '" & Me.cbo1 & "') And (tbl_Billing.TaxYr_b = '" & Me.cbo2 & "') " & _
"And (tbl_Billing.TaxPrg_b = '" & Me.cbo3 & "'))")
If tmpRS.RecordCount > 0 Then
Me.tbx2 = tmpRS.Fields(0)
Else
Me.tbx2 = 0
End If
Set tmpRS = Nothing
End Sub
Just note, I have implied all your combo boxes are returning String and the field you are comparing against are Text type. If that is not the case, you need to make changes accordingly.

Access listbox rowsource not updating via VBA

Using: MS-Access 2013; Windows 8.1 Professional
I am trying to update the displayed values in a ListBox in Access by setting the RowSource property in VBA to an SQL statement. However its not working. The listbox does not show the results of the SQL.
Here is my VBA code:
Private Sub cmbStudent_Change()
Dim s As Integer
s = cmbStudent & ""
' cmbTerm is a ListBox
cmbTerm.RowSourceType = "Table/Query"
cmbTerm.RowSource = "SELECT DISTINCT Terms.TermID, Terms.TermName " & _
" FROM Terms " & _
" ORDER BY Terms.TermCode;"
cmbTerm.Requery
End Sub
After cmbTerm.Requery, the listbox is still empty ie. its not drawing the values from the TERMS table.
Without using a RecordSet (ADODB.RecordSet) object is there any way to make this work?
Thank you in advance for any helpful inputs.
I have been having the same issue I had to fix it by putting this code at the end.
Me.Listbox.RowSourceType = "Value List"
Me.Listbox.RowSourceType = "Table/Query"
Note I had to also put it in a sub above the one that declared the RowSource.
so the RowSource is in a sub that is called by the main RowSource

Programmatically setting textbox value but returning run-time error 2115

I am trying to set the value of a text box based on the value I select in a combo box and a pre-existing value in another text box. Both the controls are in a continuous subform within a form. One key was to save the record OnDirty for Combo1, then execute the code to update TextBox1 AfterUpdate. Everything works, except that I get the following error message every time I change a value in Combo1:
Run-time error '2115':
The macro or function set to the BeforeUpdate or ValidationRule property for this field is preventing Database from saving the data in the field.
If I click 'End' on the error message, I'm fine. I have no validation rules on any elements on any of the tables connected to these forms. I am not using either the BeforeUpdate or ValidationRule properties on either the form or subform.
The code now looks like this:
Private Sub Combo1_Dirty(Cancel As Integer)
DoCmd.RunCommand acCmdSaveRecord
End Sub
Private Sub Combo1_AfterUpdate()
DoCmd.RunCommand acCmdSaveRecord
Dim con As ADODB.Connection
Set con = Application.CurrentProject.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
ssql = "(SELECT TABLE1.DESCRIPTION As d1 " & _
"FROM TABLE1 " & _
"INNER JOIN TABLE2 ON " & _
"(TABLE1.CATEGORY = TABLE2.CATEGORY) " & _
"AND (TABLE1.LEVEL = TABLE2.LEVEL) " & _
"WHERE " & _
"(((TABLE1.LEVEL)= " & [Forms]![MainForm].[Subform].Form.Combo1.Value & ") " & _
"AND ((TABLE2.CATEGORY)= '" & [Forms]![MainForm].[Subform].Form.[CATEGORY].Value & "'));)"
rs.Open ssql, con
Do Until rs.EOF = True
[Forms]![MainForm].[Subform].Form.TextBox1.SetFocus
[Forms]![MainForm].[Subform].Form.TextBox1.Text = rs.Fields!d1
rs.MoveNext
Loop
End Sub
When I click 'Debug', it highlights this line of code:
[Forms]![MainForm].[Subform].Form.TextBox1.Text = rs.Fields!d1
Again, neither the TextBox1 control or the data element underneath it have any Validation rules set, and my code is not using any BeforeUpdate (actually, not using that anywhere in the database). Any ideas why I'm getting an error, even though it's working otherwise?
Any help is greatly appreciated. Thanks!
Firstly, Dirty is called before BeforeUpdate, which is called before AfterUpdate,
so you don't need to save the record in Dirty and in AfterUpdate, I would just ditch the code for Dirty altogether since it's not really adding anything.
Try:
[Forms]![MainForm].[Subform].Form.TextBox1.Value = rs!d1
instead of
[Forms]![MainForm].[Subform].Form.TextBox1.SetFocus
[Forms]![MainForm].[Subform].Form.TextBox1.Text = rs.Fields!d1
Also, is there a particular reason you're looping through the whole recordset just to set one textbox? Does the textbox have a control source?
Wouldn't it be easier to change the subform's recordsource to rs?