Open Form in Access from Cross Table Query - ms-access

Here is the scenario. I have a database that is single function basically to manage documents. There are two tables that I am dealing with for this example.
Table 1: Table of Documents with the following fields DOCUMENT_NUM, PK; DOCUMENT_NAME; etc. One-to-many relationship to Table 1 with referential integrity based on DOCUMENT_NUM
Table 2: Table of revision history of documents with fields DOCUMENT_NUM, PK; REVISION_DATE; REVISION_NUM.
I have a form that enters in the information for Table 1, and another form that enters in information into Table 2 pulling in DOCUMENT_NUM off the criteria in Form 1.
My problem: I have a search form that I want to be able to open Form 1 that is bound to Table 1 by searching for not only parameters that are in Table 1 but also in Table 2. Example: Search for documents revised between ##/##/#### and ##/##/#### but will open Form 1 with the "DOCUMENT_NUM", "DOCUMENT_NAME", etc. However I cannot do the search since From 1 is bound to Table 1 and the information I am querying against is in Table 2.
The Search uses DoCmd.OpenForm "Documents",,,strQuery where strQuery = "1=1 AND [SOPS].[SOP_NUMBER] = 'QA-001' AND [SOP_REVISIONS].[REVISION_DATE] >= #12/02/2011# AND [SOP_REVISIONS].[REVISION_DATE] <= #12/02/2012#"
([SOPS] == Table 1 && [SOP_REVISIONS] == Table 2)

How about:
strQuery = "1=1 AND [SOPS].[SOP_NUMBER] = 'QA-001' " _
& "AND DOCUMENT_NUM IN (" _
& " SELECT DOCUMENT_NUM FROM [SOP_REVISIONS] " _
& " WHERE [SOP_REVISIONS].[REVISION_DATE] >= #12/02/2011# " _
& " AND [SOP_REVISIONS].[REVISION_DATE] <= #12/02/2012#)"
In other words, use a subquery to get the related DOCUMENT_NUM from [SOP_REVISIONS].

Related

DSUM Function Using Form Fields

I have a form which is used to submit entries to a Table.
The ‘Monthly Adjustment $’ Field currently posts new table entries which works fine.
I would like to display the total balance from the Raw Data Table in the ‘Current Balance $’ field filtered based on the Company and Accrual ID that is selected by the user in the Form.
Each time the user selects a new Company and Accrual ID combination in the Form I want the ‘Current Balance $’ field to display the total $ for that Company and Accrual combination from the Raw Data Table.
To start with I have tried using a DSUM in expression builder to sum the ‘Amount $’ field in the Raw Data table, where the Accrual ID is equal to whatever value the user has selected in the Form’s ‘Accrual ID’ field. The next step would be to then add a second filter for the company selected (which I will do once I figure this first bit out). I have included the expression I am using below.
=Nz(DSum("[Amount $]","Accruals Raw Data","[Accruals Raw Data]![Accrual ID]= ' " & [Forms]![Single Accrual Entry - Form]![Accrual ID] & " ' "))
However when I select an option in the Accrual ID field in the form it does not return any results in the Current Balance $ field. It just displays a blank box.
I can get the ‘Current Balance $’ to display the total $ amount from the table using DSUM (i.e. with no filters applied) but can’t get it to do the above.
Would appreciate your help.
Many Thanks
Remove spaces if ID is text:
=Nz(DSum("[Amount $]","Accruals Raw Data","[Accrual ID]= '" & [Accrual ID] & "'"),0)
and remove quotes too if ID is numeric:
=Nz(DSum("[Amount $]","Accruals Raw Data","[Accrual ID]= " & [Accrual ID] & ""),0)
For two criteria try:
=Nz(DSum("[Amount $]","Accruals Raw Data","[Accrual ID]= '" & [Accrual ID] & "' And [Company] = '" & [Company] & "'"),0)

Regarding fill some empty fields in access table

i have a table like this and now my task is to fill the empty field with respect to vol and country of the respective column
rule : i have to see the highest volume in the vol field and take the country of that vol and put it in the empty field (ie i have to fill empty cell with country JP because the vol of japan is more )
like this i have to fill .
the remaining fileds like RB , Plant, MCR are changing for remaining empty cells.
i had use Dlookup for this but i coudnt get the solution could any one please help me it is very helpful if you find me the solution.
like this i have to fill all empty line in the table
Ok i am giving more clear view of my table view so that you can understand easily
this is the only table i have to do the task
and now my task is i have to fill the empty cells in the country field but the condition is i should look the RB , Plant ,MCM with respect to vol field (ie: if you see the table the RB , plant ,MCM feilds are same but the country and vol are changing for one group so i have to also consider the fields, that means if the RB, plant, mcm fields are same then i have to take the one of the country in the group with the highest volume) (i just give example in the first thre rows RB , plant , MCM are same so i have to take the highest volume country ie IN so the empty cell should be IN and secodn group empty cells should be TH like that i have to fill.
As I mentioned in my comment to Johnny Bones' answer, your original requirement could have been accomplished with an UPDATE statement that used the DLookup() and DMax() functions like this:
UPDATE MyTable
SET Country=DLookup("Country","MyTable","Vol=" & DMax("Vol","MyTable"))
WHERE Country IS NULL
Even with your revised requirements it is still possible, just more scary-looking:
UPDATE MyTable
SET Country=DLookup("Country","MyTable","RB='" & RB & "' AND Plant='" & Plant & "' AND MCM='" & MCM & "' AND Country IS NOT NULL AND Vol=" & Nz(DMax("Vol","MyTable","RB='" & RB & "' AND Plant='" & Plant & "' AND MCM='" & MCM & "' AND Country IS NOT NULL"),0))
WHERE Country IS NULL
The above query was tested and verified as working in Access 2010.
You can do it in VBA, and have more control over how it reacts. Something like this will do:
Dim db As Database
Dim rec As Recordset
Dim MySQL As String
Set db = CurrentDb
Set rec = db.OpenRecordset("Select Top 1 MyTable.Country FROM MyTable ORDER BY MyTable.Vol DESC")
MyCountry = rec(0)
rec.Close
SetWarnings = False
MySQL = "UPDATE MyTable SET MyTable.Country = '" & MyCountry & "' WHERE IsNull(MyTable.Country) or Len(MyTable.Country) < 2"
DoCmd.RunSQL MySQL
SetWarnings = True
db.Close
I tested the above and it works, although if your table's field's properties are different you may need to tweak some of the code.
Obviously, anywhere you see "MyTable" you should use your own table's name.

Find Value in Last Instance of Multiple Record

I'm new to Access and SQL so I'm having a bit of trouble with this undoubtedly simple issue.
I'm using VBA and SQL to update a table based on a few listbox selections.
One of the fields I'm updating is an "instance" field which tracks the instance number of each ID. For example, the first time ID 5 was added to the table its instance number would be 1. The second time it was added to the table its instance would be 2. So it would look like this:
ID | Date | InstanceNUM |
005 | 11/22/2013 | 1 |
005 | 11/23/2013 | 2 |
and so on. It's likely that other records would/will separate the two records in the example above.
After doing some research, it seems like DLast is the best function for this job since the last instance of the particular ID will also contain the instance number in field three. However, when I use this syntax:
Dim i As Long
Dim IDnum As Long
i = DLast("[InstanceNum]", "tbl_Data", [ID] = IDnum)
'where [InstanceNum] is the field name for the value I want to return, _
'"tbl_Data" is the table name where the value I want to return exists, _
'and [ID] is the field name where the ID exists.
I get the Run-time error '94': Invalid use of Null. My understanding of this error is that DLast couldn't find a value based on this criteria (and it can't store that result in a Long data type variable), but I know that the record exists (I've checked the table for the value and I've checked the variable for the value).
EDIT
The [ID] field is a text data type. I set the IDnum variable this way:
Dim IDnum As String
Set ctlList = Me!List7
For i = 0 To ctlList.ListCount - 1
If ctlList.Selected(i) = True Then
IDnum = ctlList.Column(0, i)
Exit For
End If
Next I
The above code loops through a listbox in a form I have and sets the IDnum variable as the ID number in the first column.
Per HansUp's suggestion, I have updated my code to this:
i = DLast("InstanceNum", "tbl_Data", "[ID] =" & IDnum)
But now I get the Run-time error '3464': Data type mismatch in criteria expression.
I'm at a loss for why this is happening. Perhaps there's an easy answer to this, but I haven't been able to find one... And maybe there's an easier way to do this? Does anyone know why this error is happening?
Since [ID] is text type, add quotes around the value of IDnum for DLast.
i = DLast("InstanceNum", "tbl_Data", "[ID] = '" & IDnum & "'")
However if the stored [ID] values include leading zeros, you must Format IDnum to include those.
i = DLast("InstanceNum", "tbl_Data", "[ID] = '" & Format(IDnum, "000") & "'")

How can I find records in a table / recordset based on the result of a query on the same table?

I'm trying to return records for an alert system based on two conditions.
The first condition is there is a booking in the system for tomorrow's date [Date()+1] with a Type value of B. If that JobNumber also has a Type value (in another record) of A AND the Result field's value is "Not Approved" we need to return an alert.
Example table:
JobNumber Type Company Date Result
58129 B 3 22/03/2013
58129 A 3 20/03/2013 Not Approved
58129 C 3
So far I have been able to create a SQL query in VBA to return the results of the first condition and have looped through the results to return the relevant JobNumbers. How do I insert these JobNumbers as criteria for the second SQL query or is it possible to combine all criteria into one SQL statement?
My SQL so far:
strSQL1 = "SELECT I.JobNumber, I.Type, I.Company, I.Date, I.Result " & _
"FROM tblInspection I " & _
"WHERE (((I.Type)='B') AND ((I.Date)=Date()+1));"
strSQL2 = "SELECT I.JobNumber, I.Type, I.Company, I.Date, I.Result " & _
"FROM tblInspection I " & _
"WHERE (((I.Type)='A') AND ((I.Result)<>'approved'));"
Any help would be much appreciated.
You can get a field from the same or another table. This will give an error if more than one row is returned, but whether or not more than one row will be returned depends on your data. If it is likely, you will need to add another criterion, such as date.
SELECT I.JobNumber, I.Type, I.Company, I.Date, I.Result,
(SELECT Result
FROM tblInspection q
WHERE q.JobNumber=i.JobNumber
AND Result="Not Approved"
AND Type="A")
As ResultA
FROM tblInspection I
WHERE I.Type='B' AND I.Date=Date()+1

count and remove duplicate access vba

Here is some code I have to remove duplicate occurances of catid & recid in tblcat1_rec table, leaving only 1 entry:
mysql = "DELETE FROM tblcat1_rec "
mysql = mysql & " WHERE ID <> (SELECT Min(ID) AS MinOfID FROM tblcat1_rec AS Dupe "
mysql = mysql & " WHERE (Dupe.catid = tblcat1_rec.catid) "
mysql = mysql & " AND (Dupe.recid = tblcat1_rec.recid)); "
DoCmd.RunSQL mysql
I'd like for a count of the total amount of total duplicates found to be put into the "TL" column of the record that remains. Which would also mean, a value of 1 for records that are allready unique.
I think you will have to break this down into two parts. Firstly put the count of all the records for each catid & recid and then take 1 off. After that you can run the delete SQL statement you have here.