How to record unbound control to a database - ms-access

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"

Related

Microsoft Access - Saving New Record to Linked Database

I am creating a user interface based off of one internal and two linked (external) Access datasheets in Access 2013.
Two of the fields on my UI are combo boxes that read from the linked datasheets and display the options. This is so that the entries for suppliers and material types are called-out consistently and typos are avoided. However, I would like to add the following functionality:
-If a new value is entered into the combo box the user will be prompted to fill out the necessary information on the new value. This information will subsequently be saved to the appropriate linked datasheet.
How would I go about setting up the prompt from the combo boxes themselves? It would require Access to open a form or sub-form that will, in turn, save to the linked datasheet.
I'd prefer it to be automatic, instead of end-user prompted so that it isn't skipped. It's been years since I played around with VB, so I would like to avoid that if possible and use Access' built-in functions (even if it requires a little more time). Thank you in advance!
Alright, so I was able to do it after researching the "OnNotInList" function and a little VB code.
In the OnNotInList section of the 'Event' properties sheet, I chose 'Code Builder' and entered the following:
Private Sub Supplier_NotInList(NewData As String, Response As Integer)
Dim ctl As Control
Dim dbsCustomerDatabase As Database
On Error GoTo Supplier_NotInList_Err
Dim intAnswer As Integer
Dim strSQL As String
intAnswer = MsgBox("The supplier " & Chr(34) & NewData & _
Chr(34) & " is not currently listed." & vbCrLf & _
"Would you like to add it to the list now?" _
, vbQuestion + vbYesNo, "Spire Manufacturing Solutions")
' Adding the new entry to the list:
If intAnswer = vbYes Then
strSQL = "INSERT INTO CustomerList([CustomerName]) " & _
"VALUES ('" & NewData & "');"
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
MsgBox "The new supplier has been added to the list." _
, vbInformation, "Spire Manufacturing Solutions"
Response = acDataErrAdded
' Opening the Supplier datasheet to add details
' to the new entry:
MsgBox "Opening Supplier database for new entry..."
DoCmd.OpenTable "CustomerList", acViewNormal, acEdit
End If
Supplier_NotInList_Exit:
Exit Sub
Supplier_NotInList_Err:
MsgBox Err.Description, vbCritical, "Error"
Resume Supplier_NotInList_Exit
End Sub
This allowed me to automatically prompt the user to add the details for a new supplier if they enter a new supplier name. Or, cancel the entry if they simply misspelled it. I'd quite forgotten how versatile VB was. Thank you all for your assistance in getting me headed in the right direction!

Auto Populate Access Form using simple VBA code by setting a variable

I was recently given the task of creating a form that will autofill with the information from a table. The information the form autofills is selected using a primary key called ModID. I have a combo box that has a List of the ModIDs that are listed as Active.
SELECT ModID
FROM P_Review
WHERE Status = "Active"
Simple enough. I then have VBA code running on the event After Update. So after the value for the combo box is select or changed it will run this VBA code.
Option Compare Database
Option Explicit
Private Sub selectModID_AfterUpdate()
'Find the record that matches the control.
On Error GoTo ProcError
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
.FindFirst "ModID=" & Me.selectModID
If Not .NoMatch Then
Me.Bookmark = .Bookmark
Else
DoCmd.RunCommand acCmdRecordsGoToNew
Me!localModID = Me.selectModID.Column(0)
End If
End With
ExitProc:
Exit Sub
ProcError:
MsgBox "Error: " & Err.Number & ". " & Err.Description
Resume ExitProc
End Sub
The code runs fine (I get no errors when I debug or run).
Now for the access text box. I would like to populate certain fields based off the variable localModID. I have a dlookup in a text box to find the information in the table P_Review.
=DLookUp("Threshold","P_Review","ModID =" & [localModID])
So the DlookUp should find the value for the column threshold, in the table P_Review, where the ModID in P_Review equals the localModID set in the VBA code. But when I go to form view and select a ModID I get the Error 3070: The Microsoft Access database engine does not recognize as a valid field name or expression. I did copy this code from another database we are already using but it fails in this new instance.
Private Sub ModID_AfterUpdate()
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
.FindFirst "ModID='" & Me.ModID & "'"
If Not .NoMatch Then
Me.Bookmark = .Bookmark
Else
DoCmd.GoToRecord , , acNewRec
Me!ModID = Me.ModID
End If
End With
End Sub
This is the answer to question. I used this code to auto update.
Try
Forms!<whatever_this_form_name_is>![localModID]
in your DLOOKUP

Add Criteria To VBA Code and Requery

So the following VBA code I have will requery the form based on the Combo1 value equal to January. Eventually, I'll have X number of years in the Combo value and only want to display all records based on each year.
Is it possible to add additional VBA code to use the Criteria from the query instead of having X amount of queries and requery them based on the year.
Private Sub Combo1_AfterUpdate()
If Combo1.Value = "2013" Then
[Form_Main Form].RecordSource = "Main_Form_Query"
[Form_Main Form].Requery
End If
End Sub
You can construct the query in runtime (remember: a query object in access is just an sql statement)
So, let's asume that your data is stored in a table called tblMyData that has columns called month (String, month name) and year (Numeric, Integer) (just examples). You can generate the SQL query in VBA this way:
...
Dim strSQL as String
...
strSQL = "SELECT * FROM tblMyData " & _
"WHERE month='" & ComboMonth.Value & "' " & _
" AND year=" & ComboYear.Value ";"
...
[Form_Main Form].RecordSource = strSQL
[Form_Main Form].Requery
...
Hope this helps you.
Open the form in a different way.
DoCmd.OpenForm "MyForm",,,"MyYear=2013"
Or
DoCmd.OpenForm "MyForm",,,"MyYear=" & Me.MyCombo
Assuming that MyYear in the table or query is numeric. If it is not, you can use single quotes.
The general idea is that you use a form with all records, and use the Where argument of OpenForm to specify the records that should be shown. You can do the same with reports.
I have only a vague idea about what you're trying to accomplish. It might help to show us the SQL from Main_Form_Query. Meanwhile, consider whether you can use the form's .Filter property to do what you need.
If the form's Record Source includes a text field named fiscal_year, you could filter the rows displayed based on the year selected in your combo box.
Private Sub Combo1_AfterUpdate()
' .Value is the default property, so not required after Me.Combo
Me.Filter = "fiscal_year = '" & Me.Combo1 & "'"
Me.FilterOn = True
End Sub
Yet another approach could be to reference the combo value in Main_Form_Query.
WHERE
Forms!YourForm!Combo1 Is Null
OR some_field = Forms!YourForm!Combo1
Then do Me.Requery in the combo's After Update event.

Runtime query does not work.Why?

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 : )

MS Access 03 Query using Yes/No Data Type

I have a table in Access..
AccessKey
AccessCardID
Distributed (yes/no)
On my form is a combo box with 10 Access Cards. I need help setting up a query where if guest A gets Access Card #1, the user will only be able to choose from Access Cards #2-#10, for guest B, c, and so on, until guest A returns Access Card #1.
so far the the query i have is
SELECT AccessCardID
FROM AccessKey
WHERE Distributed = False;
Here is my new code for After update
Private Sub AccessKeyNo_AfterUpdate()
If MsgBox("Do you want to assign Access Key" & Me.AccessKeyNo & "?", _
vbYesNo) = vbYes Then
Me.GuestAccessKeyID = Me.AccessKeyNo
Me.MyCheckBox = Not IsNull(Me.GuestAccessKeyID)
Me.AccessKeyNo.Requery
End If
End Sub
My new query
SELECT AccessKey.AccessKeyID
FROM AccessKey LEFT JOIN Guest ON AccessKey.AccessKeyID=Guest.GuestAccessKeyID
WHERE (((Guest.GuestAccessKeyID) Is Null));
And the On current for the form
Private Sub Form_Current()
Me.MyCheckBox = Not IsNull(Me.GuestAccessKeyID)
If IsNull(Me![GuestID]) Then
DoCmd.GoToControl "GuestFirstName"
End If
End Sub
Why don't you set Distributed to False in the above query so that you get the list of cards which have not been distributed yet.
If you do not like writing code, you can use a subform and set the record source to your table, AccessKey. Alternatively you can write a little code, say:
Private Sub NameOfComboHere_AfterUpdate()
Dim db As Database
Dim strSQL As String
Set db = CurrentDb
If MsgBox("Do you want to assign " & Me.NameOfComboHere & "?", _
vbYesNo) = vbYes Then
strSQL = "UPDATE AccessKey SET Distributed = True " _
& "WHERE AccessCardID = " & Me.NameOfComboHere
db.Execute strSQL, dbFailOnError
If db.RecordsAffected = 1 Then
MsgBox Me.NameOfComboHere & " has been assigned."
End If
End If
Me.NameOfComboHere.Requery
End Sub
There are a few notes. This assumes that the combobox has a bound column of AccessCardID and that AccessCardID is numeric. It also assumes that you have a reference to Microsoft DAO 3.x Object library. A subform may be the best bet.
EDIT based on Comments
Let us say you have a card id in the guest table, first, add a little code to the Current event for the form:
Me.MyCheckBox = Not IsNull(Me.GuestAccessCard)
This will set the checkbox to false if there is no card id and to true if there is an id.
You will need to change the query for the combobox to:
SELECT AccessCardID
FROM AccessKey
LEFT JOIN Guests
ON AccessKey.AccessCardID = Guest.GuestAccessCard
WHERE Guest.GuestAccessCard Is Null
Then the After Update event would run:
Private Sub NameOfComboHere_AfterUpdate()
If MsgBox("Do you want to assign " & Me.NameOfComboHere & "?", _
vbYesNo) = vbYes Then
Me.GuestAccessCard = Me.NameOfComboHere
Me.MyCheckBox = Not IsNull(Me.GuestAccessCard)
''The data will have to be saved for the
''combo to update with the new data
If Me.Dirty Then Me.Dirty = False
Me.NameOfComboHere.Requery
End If
End Sub
And do not forget to set the GuestAccessCard to Null when the checkbox is unticked and requery the combo.
I may be completely misunderstanding the situation here, but it seems to me that you don't want to have a Boolean field in the table with your cards to indicate if it's checked out -- all you need is a field in your Guests table where you enter the card number. Then you can tell which cards are available with a left join against the card numbers that are in use:
SELECT Cards.CardNumber
FROM Cards LEFT JOIN Guests ON Cards.CardNumber = Guests.CardNumber
WHERE Guests.CardNumber Is Null
This would mean that there's only ever one place where the information is stored (in the Guests table). You could also put a unique index on the CardNumber field in the Guests table (allow Nulls) so you could never assign the same card to two guests.
This may be the way you are doing things, or the way Remou has suggested, but I got too confused by all the convoluted back and forth!