MS ACCESS how to change a query criteria to look up a record and then create a report - ms-access

enter image description herei have a program that create field tickets, when the ticket is finished i can see it in a list box name FinishedJobs, when i double click on a ticket inside the listbox it ask me if i want to reopen it or send it to print. The first one (reopen) is done but the second one i can't get it to work.
The problem is i have the ticket number in a variable named strCriteria and i want to use that value and put it in the criteria inside the query name JobsTicketGeneralReport, so i can open a report using that query.
PLEASE HELP ME TO CHANGE THE CRITERIA IN THE QUERY TO SEARCH MY TICKET NUMBER. I'M WILLING TO CHANGE THE CODES IF YOU SUGGEST THAT.
NOTE: My query is a combine query it has 6 tables and has the ticket number in common, when i call the ticket number it bring the information of all tables.
This what i am doing:
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rst As Recordset
Dim varItem As Variant
Dim strCriteria As String
Dim qdfOld As String
Dim strSQL As String
' Get the database and stored query
Set db = CurrentDb()
Set qdf = db.QueryDefs("JobsticketGeneralReport")
' Loop through the selected items in the list box and build a text string
For Each varItem In Me!List0.ItemsSelected
strCriteria = strCriteria & ",'" & Me.List0.Column(0) & "'"
Next varItem
' Check that user selected something
If Len(strCriteria) = 0 Then
MsgBox "You did not select anything from the list" _
, vbExclamation, "Nothing to find!"
Exit Sub
End If
'Debug.Print strCriteria
' Remove the leading comma from the string
strCriteria = Right(strCriteria, Len(strCriteria) - 1)
Debug.Print strCriteria
' change criteria in query
qdf.Parameters(0).Value = Trim(strCriteria)
Set rst = qdf.OpenRecordset
DoCmd.OpenQuery "JobsticketgeneralReport"
DoCmd.OpenReport "JobsticketgeneralReport", acpreview
rst.Close
qdf.Close
Set rst = Nothing
Set qdf = Nothing
HERE IS MY SQL:
SELECT JobsOrder.StartDigDate, JobsOrder.Ticket, JobsOrder.DigNumber, JobsOrder.JobType,
JobsOrder.JobAddressNumber, JobsOrder.JobAddressName, JobsOrder.JobAddressTown,
JobsOrder.JobDescription, JobsOrder.AssetID, JobsOrder.Notes, JobsOrder.FINISH,
JobsOrder.updateGIS, JobsOrder.Priority, GENERAL.STARTJOBDATE, GENERAL.ENDJOBDATE,
GENERAL.DAY1, GENERAL.DAY2, GENERAL.EMPLOYEE0, GENERAL.EMPLOYEE1, GENERAL.EMPLOYEE2,
GENERAL.EMPLOYEE3, GENERAL.EMPLOYEE4, GENERAL.EMPLOYEE5, GENERAL.EMPLOYEE6,
GENERAL.EMPLOYEE7, GENERAL.VEHICLE0, GENERAL.VEHICLE1, GENERAL.VEHICLE2,
GENERAL.VEHICLE3, GENERAL.VEHICLE4, GENERAL.VEHICLE5, GENERAL.EMPLOYEE0TIME,
GENERAL.EMPLOYEE1TIME, GENERAL.EMPLOYEE2TIME, GENERAL.EMPLOYEE3TIME,
GENERAL.EMPLOYEE4TIME, GENERAL.EMPLOYEE5TIME, GENERAL.EMPLOYEE6TIME,
GENERAL.EMPLOYEE7TIME, GENERAL.DRAWINGATT, GENERAL.FINISH, GENERAL.ASPHALT,
GENERAL.ROW, GENERAL.CONCRETE, GENERAL.DIRT, GENERAL.TRENCH, MAINS.[JOBTYPE-MAIN],
MAINS.MATERIAL, MAINS.SIZE, MAINS.DEPTH, MAINS.INTERNALCONDITION, MAINS.COMMENTS,
MAINS.REPAIRLOCATION, MAINS.LOCATION1, MAINS.LOCATION2, MAINS.MATERIAL1,
MAINS.MATERIAL2, MAINS.MATERIAL3, MAINS.MATERIAL4, MAINS.MATERIAL5,
MAINS.MATERIAL6, MAINS.MATERIAL7, MAINS.MATERIAL8, MAINS.MATERIAL9,
MAINS.MATERIAL10, MAINS.MATERIAL11, MAINS.MATERIAL12, MAINS.QTY1, MAINS.QTY2,
MAINS.QTY3, MAINS.QTY4, MAINS.QTY5, MAINS.QTY6, MAINS.QTY7, MAINS.QTY8,
MAINS.QTY9, MAINS.QTY10, MAINS.QTY11, MAINS.QTY12, MAINS.ENABLE, SERVICES.JOBPERFORMBY,
SERVICES.SERVICEASSET, SERVICES.OFFON, SERVICES.[MATERIAL-MC], SERVICES.[SIZE-MC],
SERVICES.[DEPTH-MC], SERVICES.[MATERIAL-CB], SERVICES.[SIZE-CB], SERVICES.[DEPTH-CB],
SERVICES.CURBBOXLOCATION, SERVICES.LOCATION1, SERVICES.LOCATION2, SERVICES.LOCATION3,
SERVICES.[SERVICE-COMMENT], SERVICES.[MATERIAL1-MC], SERVICES.[MATERIAL2-MC],
SERVICES.[MATERIAL3-MC], SERVICES.[MATERIAL4-MC], SERVICES.[MATERIAL5-MC],
SERVICES.[MATERIAL6-MC], SERVICES.[MATERIAL7-MC], SERVICES.[MATERIAL8-MC],
SERVICES.[QTY1-MC], SERVICES.[QTY2-MC], SERVICES.[QTY3-MC], SERVICES.[QTY4-MC],
SERVICES.[QTY5-MC], SERVICES.[QTY6-MC], SERVICES.[QTY7-MC], SERVICES.[QTY8-MC],
SERVICES.[MATERIAL1-CB], SERVICES.[MATERIAL2-CB], SERVICES.[MATERIAL3-CB],
SERVICES.[MATERIAL4-CB], SERVICES.[MATERIAL5-CB], SERVICES.[MATERIAL6-CB],
SERVICES.[MATERIAL7-CB], SERVICES.[MATERIAL8-CB], SERVICES.[QTY1-CB],
SERVICES.[QTY2-CB], SERVICES.[QTY3-CB], SERVICES.[QTY4-CB], SERVICES.[QTY5-CB],
SERVICES.[QTY6-CB], SERVICES.[QTY7-CB], SERVICES.[QTY8-CB], SERVICES.REPAIR,
SERVICES.Replace, SERVICES.INSTALL, SERVICES.REMOVE, SERVICES.TEMPDISCONNECT,
SERVICES.ENABLE, HYDRANT.[ENABLE-H], HYDRANT.[HYDRANT-ASSET], HYDRANT.[REPAIR-H],
HYDRANT.[REPLACE-H], HYDRANT.[INSTALL-H], HYDRANT.FLUSH, HYDRANT.FLOWTEST,
HYDRANT.PARTS1, HYDRANT.PARTS2, HYDRANT.PARTS3, HYDRANT.PARTS4, HYDRANT.PARTS5,
HYDRANT.PARTS6, HYDRANT.PARTS7, HYDRANT.PARTS8, HYDRANT.[QTY1-H], HYDRANT.[QTY2-H],
HYDRANT.[QTY3-H], HYDRANT.[QTY4-H], HYDRANT.[QTY5-H], HYDRANT.[QTY6-H],
HYDRANT.[QTY7-H], HYDRANT.[QTY8-H], HYDRANT.JOBPERFORM, HYDRANT.[MANUFACTORY OLD],
HYDRANT.MANUFACTORY, HYDRANT.SIZENEW, HYDRANT.SIZEOLD, HYDRANT.JOBNOTES,
HYDRANT.TIMEOPEND, HYDRANT.TIMECLOSED, HYDRANT.TIMETOCLEAR, HYDRANT.COLOROPEN,
HYDRANT.COLORCLOSE, HYDRANT.REMARKS, HYDRANT.[STATIC-PRESSURE], HYDRANT.[RESIDUAL-PRESSURE],
HYDRANT.[PITOT-TESTFLOWRATE], HYDRANT.CAPACITY, HYDRANT.[ASSET-ID1],
HYDRANT.[ASSET-ID2], VALVES.ENABLE, VALVES.[REPAIR-V], VALVES.[REPLACE-V],
VALVES.[INSTALL-V], VALVES.[REMOVE-V], VALVES.[MAINTENANCE-V], VALVES.VALVECOMMENT,
VALVES.[MATERIAL1-V], VALVES.[MATERIAL2-V], VALVES.[MATERIAL3-V], VALVES.[MATERIAL4-V],
VALVES.[MATERIAL5-V], VALVES.[MATERIAL6-V], VALVES.[QTY1-V], VALVES.[QTY2-V],
VALVES.[QTY3-V], VALVES.[QTY4-V], VALVES.[QTY5-V], VALVES.[QTY6-V],
VALVES.[LOCATION1-V], VALVES.[LOCATION2-V], VALVES.[LOCATION3-V], VALVES.[LOCATION4-V],
VALVES.VALVE1, VALVES.VALVE2, VALVES.VALVE3, VALVES.VALVE4, VALVES.VALVE5,
VALVES.VALVE6, VALVES.VALVE7, VALVES.VALVE8, VALVES.VALVEPOSITION1,
VALVES.VALVEPOSITION2, VALVES.VALVEPOSITION3, VALVES.VALVEPOSITION4,
VALVES.VALVEPOSITION5, VALVES.VALVEPOSITION6, VALVES.VALVEPOSITION7,
VALVES.VALVEPOSITION8, VALVES.[VALVE-TURNS1], VALVES.[VALVE-TURNS2],
VALVES.[VALVE-TURNS3], VALVES.[VALVE-TURNS4], VALVES.[VALVE-TURNS5],
VALVES.[VALVE- TURNS6], VALVES.[VALVE-TURNS7], VALVES.[VALVE-TURNS8],
VALVES.[VALVE-DEPTH1], VALVES.[VALVE-DEPTH2], VALVES.[VALVE-DEPTH3],
VALVES.[VALVE-DEPTH4], VALVES.[VALVE-DEPTH5], VALVES.[VALVE-DEPTH6],
VALVES.[VALVE-DEPTH7], VALVES.[VALVE-DEPTH8], VALVES.REASON1, VALVES.REASON2,
VALVES.REASON3, VALVES.REASON4, VALVES.REASON5, VALVES.REASON6, VALVES.REASON7,
VALVES.REASON8, INSPECT.ENABLE, INSPECT.[CURBBOX-I], INSPECT.[VALVEBOX-I],
INSPECT.[SERVICE-I], INSPECT.CURBBOXREMARKS, INSPECT.VALVEBOXREMARKS, INSPECT.SERVICEREMARKS
FROM (((((JobsOrder
INNER JOIN [GENERAL] ON JobsOrder.Ticket = GENERAL.TICKET)
INNER JOIN MAINS ON GENERAL.TICKET = MAINS.TICKET)
INNER JOIN SERVICES ON MAINS.TICKET = SERVICES.TICKET)
INNER JOIN HYDRANT ON SERVICES.TICKET = HYDRANT.TICKET)
INNER JOIN VALVES ON HYDRANT.TICKET = VALVES.TICKET)
INNER JOIN INSPECT ON VALVES.TICKET = INSPECT.TICKET
WHERE (((JobsOrder.Ticket)=[ticket])
AND ((JobsOrder.FINISH)=True))
ORDER BY JobsOrder.StartDigDate, JobsOrder.Ticket;

If you want to use a parameter in the query, you should explicitly define it. Also, it is a good idea to give the parameter a different name than the involved tables and fields.
To do this, use the "Parameters" window in query design, or add a PARAMETERS clause to the beginning of the SQL:
PARAMETERS parTicket Text ( 255 );
SELECT .....
and in the WHERE clause
WHERE (((JobsOrder.Ticket)=[parTicket])
This is mainly useful if you want to read data from the query in VBA, i.e. you need this for
Set rst = qdf.OpenRecordset
But if the query is RecordSource for a report, this won't work, because the report opens its own instance of the query. In this case, you need Parfait's solution: directly use the listbox in the query.
WHERE ((JobsOrder.Ticket) = Forms!yourForm!List0)

For Each varItem In Me!List0.ItemsSelected
strCriteria = strCriteria & ",'" & Me.List0.Column(0) & "'"
Next varItem
This cannot work - you must use varItem in the loop.
Me.List0.Column(0) will always pick the same element.
Debug.Print strCriteria
This should have told you what went wrong.

Related

Create a query from a button on a form

I have a form with a button on it.
I want the button to create a query from a table (which the form populates)
I made the button, went to the code builder
Private sub button123_on click()
End sub
I've looked up queries in DOA but i cant figure it out, or even know if that is what im supposed to be using. I just need to know what comes after private sub
If statements?
Dim stuff?
doCmd?
🤷🏾‍♂️
Im just looking for the basic layout
Do i build the query elsewhere and then put a command to run it for the button? It has to be in VBA because i need to select the TOP variable# of records. The TOP changes so i cant do it in sql.
After some research this is my code
Private Sub Command487_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb
Dim varX As Variant
Set qdef = db.CreateQueryDef("MyQuery")
Application.RefreshDatabaseWindow
varX = DLookup("[Quantity1]", "tblFilledRequests", "[OrderID] = [Forms]![frmFilledRequests]![OrderID]")
strSQL = "SELECT TOP varX tblFilledRequests.OrderID, tblFilledRequests.RequestFillDate, tblFilledRequests.Issuer, tblFilledRequests.Unit, tblFilledRequests.ContactNumber, tblFilledRequests.CommonName1, tblFilledRequests.Quantity1, tblFilledRequests.CommonName2, tblFilledRequests.Quantity2, tblWeapons.IssueCount, tblWeapons.StockNumber, tblWeapons.SerialNumber, tblWeapons.Status " _
& "FROM tblWeapons INNER JOIN tblFilledRequests ON tblWeapons.WeaponID = tblFilledRequests.CommonName1 " _
& "WHERE (((tblFilledRequests.OrderID)=Forms!frmFilledRequests!OrderID) And ((tblWeapons.Status)=""AVAILABLE"")) " _
& "ORDER BY tblWeapons.IssueCount, tblWeapons.StockNumber;"
qdf.SQL = strSQL
DoCmd.OpenQuery "MyQuery"
qdf.Close
Set qdef = Nothing
Set db = Nothing
End Sub
I get a blank query and i get an error message qdf.SQL object variable or with block variable not set
I'm going to assume that you want to execute that query and display the results in an element on your form, for example, a listbox.
I've made a form with:
A textbox named txtTopX that will allow the user to input the amount of records they want to retrieve.
A button that will execute the query and show the results (btnQuery)
A listbox that will display the results. I've named it lstResults and set the Column Count property to the amount of columns my query will return. (in this example, 3)
The code on the form is this:
Private Sub btnQuery_Click()
Dim limit As Integer
'Determine the TOP X limit
If IsNumeric(Me.txtTopX.Value) Then
limit = Me.txtTopX.Value
Else
limit = 5 'Some default value incase the input from the textbox is not a number
End If
'Set the rowsource of the listbox to the query's results
lstResults.RowSource = "SELECT TOP " & limit & " col1, col2, col3 FROM Table1 ORDER BY ID DESC"
End Sub
The table in this example is Table1 and has 4 columns: ID, col1, col2 and col3. In my query I'm only showing 3 columns and using the ID column to sort my records on. (as you're planning to use TOP X, I think you want to show the TOP X most recent records)
thank you for the advice, Grimlor.
no, i am not trying to display the results of the query on the current form. I actually need to display them in an array on another form, but that is a little down the road.
i need to write the query in VBA
for my TOP I used the DLookup function. and defined varX as a variable
varX = DLookup("[Quantity1]", "tblFilledRequests", "[OrderID] = [Forms]!
[frmFilledRequests]![OrderID]")
i will take what i can from your answer
Private Sub Command490_Click()
Dim db As DAO.Database
Set db = CurrentDb
Dim qdf As DAO.QueryDef
Dim strSQL As String
Dim limit As Integer
limit = Me.Quantity1.Value
On Error Resume Next
DoCmd.DeleteObject acQuery, "testQry"
On Error GoTo 0
strSQL = "SELECT TOP " & limit & " tblFilledRequests.OrderID,
tblFilledRequests.RequestFillDate, tblFilledRequests.Issuer,
tblFilledRequests.Unit, tblFilledRequests.ContactNumber,
tblFilledRequests.CommonName1, tblFilledRequests.Quantity1,
tblFilledRequests.CommonName2, tblFilledRequests.Quantity2, tblWeapons.IssueCount,
tblWeapons.StockNumber, tblWeapons.SerialNumber, tblWeapons.Status " & vbCrLf & _
"FROM tblWeapons INNER JOIN tblFilledRequests ON tblWeapons.WeaponID =
tblFilledRequests.CommonName1 " & vbCrLf & _
"WHERE (((tblFilledRequests.OrderID)=[Forms]![frmFilledRequests]![OrderID]) AND
((tblWeapons.Status)=""AVAILABLE"")) " & vbCrLf & _
"ORDER BY tblWeapons.IssueCount, tblWeapons.StockNumber;"
Set qdf = db.CreateQueryDef("testQry", strSQL)
DoCmd.OpenQuery ("testQry")
End Sub
It all works beautifully. Thank you

Loop through records and increment value in vba access

I'm trying to loop through records in a table with part no's and with matching part no's, increment a value in the pos field. I asked a question earlier(Object variable or With block variable not set Access vba) with the same project but for a different step of the process (running a query). I haven't found a question that addresses this problem in Access yet, but I have taken some pointers from this question: Code to loop through all records in MS Access . Now, I'm trying to write the code to loop through the records and increment the value in the pos field.
The query that will run:
SELECT CTOL.ID, CTOL.BOM_PART_NAME, CTOL.CII, CTOL.[PART FIND NO], CTOL.CSN, CTOL.AFS, CTOL.EQP_POS_CD, CTOL.LCN, CTOL.POS_CT, CTOL.SERIAL_NO, CTOL.PART_NO_LLP, [CTOL_Asbuilt].[PART-SN], [CTOL_Asbuilt].[PART-ATA-NO], [CTOL_Asbuilt].[PW-PART-NO]
FROM CTOL LEFT JOIN [CTOL_Asbuilt] ON CTOL.[PART FIND NO] = [CTOL_Asbuilt].[PART-ATA-NO];
Code so far (credit to Kostas K for helping me on the other question):
Option Compare Database
Option Explicit
'Const adOpenStatic = 3
'Const adLockOptimistic = 3
Function queryDatabase()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qdf As QueryDef
'Dim rsQuery As DAO.Recordset
Dim rows As Variant
Dim part_find_no() As String
Dim eqp_pos() As Integer
'Dim strSQL As String
Dim i As Integer
Dim j As Integer
'Set objConnection = CurrentDb.OpenRecordset("CTOL")
Set db = CurrentDb
Set qdf = db.QueryDefs("SicrProcess")
Set rs = qdf.OpenRecordset(dbOpenDynaset)
If rs.EOF Then GoTo Leave
rs.MoveLast
rs.MoveFirst
For i = 1 To rs.RecordCount
Debug.Print rs.Fields("PART FIND NO") & " " & rs.Fields("EQP_POS_CD")
rs.MoveNext
Next i
Leave:
On Error Resume Next
rs.Close
Set rs = Nothing
qdf.Close
Set qdf = Nothing
Set db = Nothing
On Error GoTo 0
Exit Function
ErrProc:
MsgBox Err.Description, vbCritical
Resume Leave
End Function
The two fields I want to loop through are PART FIND NO in the CTOL table and EQP_POS_CD in the CTOL table. The value in EQP_POS_CD should be incremented by 1 if the last PART FIND NO is identical to the current no. The result set should contain the other fields selected in the query as well. Is there anything else I need to add to get it output? Right now, I'm not too concerned as to how it's output, whether in a window or in datasheet format (though I would appreciate pointers on this if anyone knows). Any pointers on how to accomplish this? Also, if there's anything I'm missing in my question that's important, or if there's something I could do better when posting a question, I'm open to discussing it. I'm also open to discussion of how to approach the problem. Thanks!
Possibly:
SELECT CTOL.*, [CTOL_Asbuilt].[PART-SN], [CTOL_Asbuilt].[PART-ATA-NO], [CTOL_Asbuilt].[PW-PART-NO],
DCount("*", "CTOL", "[Part Find No]=" & [Part Find No] & " AND ID<" & [ID])+1 AS Seq
FROM CTOL LEFT JOIN [CTOL_Asbuilt] ON CTOL.[PART FIND NO] = [CTOL_Asbuilt].[PART-ATA-NO];

Microsoft Access 2010 interdependencies in Forms (fill out one cell, automatically fill another)

In excel, I know this is the VLOOKUP function, however, being a beginner at Access, I have no clue how to do this.
I have halls (from A to H), who all have their own teamleader (eg A-->Ben, B-->Michael, C-->Dave, etc). I would like to select just the hall, and the teamleader will automatically show up in the next field on the form. At the end, all will be registered in a table.
I have currently build this equation to fill out a specific value in a cell (dependent on the value of another cell), but it is giving an error message. What am I doing wrong?
Option Compare Database
Dim db As DAO.Database
Dim rst As DAO.Recordset
Private Sub Hal_AfterUpdate()
Set db = CurrentDb
'SELECT Voormannen.Voorman, Voormannen.Hal
'FROM Voormannen
'WHERE (((Voormannen.Hal)=[Formulieren]![DSM formulier]![Hal]));
strSQL = "SELECT Voormannen.Voorman, Voormannen.Hal FROM Voormannen WHERE [Voormannen]![Hal]=[Forms]![DSM formulier]![Hal]"
Set rst = db.OpenRecordset(strSQL)
rst.MoveFirst
Me.Tekst304 = rst![Voorman]
rst.Close
Set rst = Nothing
Me.Refresh
End Sub
Assuming your SQL string returns a correct dataset, try replacing this:
Me.Tekst304 = rst![Voorman]
with this:
Me.Tekst304.Text = rst("Voorman")
If your SQL string does not return a correct dataset, try changing it to this:
strSQL = "SELECT Voorman, Hal FROM Voormannen " & _
"WHERE Hal = '" & Forms![DSM formulier]!Hal.Text & "'"
You need to surround your control reference with ampersands (&) otherwise VBA doesn't know you're referencing a control.

MS Access out of stack space when creating query

I am trying to create an Access database that will link together multiple structurally identical databases together. These other databases are exports from a 3D model that have identical tables, but different data in each. What I need to do is report from all the database like they are one big database. How I thought I would approach this is to create queries that would union the individual identical tables from each database into one query, which I could then use in all my other reports. the code I wrote to join the tables together is below. The trouble I'm running into is that , this code gives me an out of stack space error on the "Set QueryDef..." line. Can someone tell me what I'm doing wrong?
Public Sub CreateUnionQueries()
'On Error GoTo Err_CreateUnionQueries
Dim QueryRs As DAO.Recordset
Dim TableRs As DAO.Recordset
Dim QueryDef As DAO.QueryDef
Dim SQLText As String
Dim qry As QueryDef
'Get list of all Foreign Table Names
Set QueryRs = CurrentDb.OpenRecordset("select distinct ForeignName from msysobjects where ForeignName is not null")
'Loop over list to create union queries
If QueryRs.RecordCount <> 0 Then
Do While Not QueryRs.EOF
Set TableRs = CurrentDb.OpenRecordset("select Name from msysobjects where ForeignName = """ & QueryRs![ForeignName] & """")
Do While Not TableRs.EOF
SQLText = SQLText & "select * from " & TableRs![Name]
TableRs.MoveNext
If Not TableRs.EOF Then
SQLText = SQLText & " UNION ALL "
End If
Loop
'Create union query
For Each qry In CurrentDb.QueryDefs
If qry.Name = "Q-" & QueryRs![ForeignName] Then
DoCmd.DeleteObject acQuery, "Q-" & QueryRs![ForeignName]
End If
Next qry
Set QueryDef = CurrentDb.CreateQueryDef("Q-" & QueryRs![ForeignName], SQLText)
QueryDef.Close
Set QueryDef = Nothing
QueryRs.MoveNext
TableRs.Close
Set TableRs = Nothing
Loop
Else
MsgBox "No files are linked currently"
End If
QueryRs.Close
Err_CreateUnionQueries:
MsgBox "We have an error"
Set QueryRs = Nothing
Set TableRs = Nothing
Exit Sub
End Sub
Oh man, I'm an idiot. Found the problem. When I was looping, I wasn't setting SQLText back to empty, so it was appending my query for table group onto the last. Removed that and now it works as expected. Thank you guys for your help.

Access VBA Loop through Query help

I have a form (Cobind_frmMain) that allows the user to create a pool of titles that are attached to it. So there is a top level Pool Name (TopLvlPoolName) and on a subform, the titles are added to it. What I need is to issue a Report for each of the titles. I have the report and queries all set up. Right now, the report will show all the titles in one file. The titles are in a field called "CatCode".
What I need is the following:
1. Save each title as a PDF and save it to our server.
2. Open email and attach the PDF.
3. Repeat until all titles are done.
EDIT: This is what I have so far for code and the error message I still get is: "Too Few Parameters" on the Set Recordset line. I'm trying to set the parameter in the strSQL line. I want the PartPoolName (in Cobind_qryReport, a query) to equal the TopLvlPoolName on the open form. The SQL for Cobind_qryReport is listed below:
Private Sub btn_Run_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "Select * FROM Cobind_qryReport WHERE PartPoolName = " & Me.TopLvlPoolName
Set rs = db.OpenRecordset(strSQL)
On Error GoTo Err_PO_Click
If MsgBox("Do you wish to issue the cobind invites?", vbYesNo + vbQuestion, "Confirmation Required") = vbYes Then
rs.MoveFirst
Do While Recordset.EOF = False
DoCmd.OutputTo acOutputReport, "Cobind_rptMain", acFormatPDF, "K:\OB MS Admin\Postage\CoBind Opportunities\Sent Invites\" & [CatCode] & "_" & [PartPoolName] & "Cobind Invite_" & Format(Now(), "mmddyy") & ".pdf"
DoCmd.SendObject acSendReport, "Cobind_rptMain", acFormatPDF, , , , [CatCode] & "_" & [PartPoolName] & " Cobind Invite", "Please find the cobind invite attached. Response is needed by " & [RSVP] & ". Thank you.", True
Recordset.MoveNext
Loop
End If
Exit_PO_Click:
MsgBox ("It didn't work")
Exit Sub
Err_PO_Click:
MsgBox Err.Description
Resume Exit_PO_Click
End Sub
Cobind_qryReport SQL:
SELECT tblEvents.EventTitle, Cobind_tblPartic.CatCode, Cobind_tblPartic.CodeQty, Cobind_tblPartic.PartPoolName, Cobind_tblTopLvl.RSVP, Cobind_tblPartic.ID
FROM Cobind_tblTopLvl, Cobind_tblPartic INNER JOIN tblEvents ON Cobind_tblPartic.CatCode = tblEvents.EventCode
GROUP BY tblEvents.EventTitle, Cobind_tblPartic.CatCode, Cobind_tblPartic.CodeQty, Cobind_tblPartic.PartPoolName, Cobind_tblTopLvl.RSVP, Cobind_tblPartic.ID
ORDER BY Cobind_tblPartic.ID;
Thank you again for all your help!
You're query Cobind_qryReport has a parameter that you need to set. if you want to know the parameter name try the following code
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("Cobind_qryReport")
If qdf.Parameters.Count > 0 Then
MsgBox (qdf.Parameters(0).Name)
End If
Update
Since you know you've got a parameter doing select * from Cobind_qryReport it might just be easier to set the parameter and then use the qdf to open the recordset e.g.
Dim rs as DAO.Recordset
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("Cobind_qryReport")
qdf.Parameters(0).Value = 7832
Set foo = qdf.OpenRecordset()
Note: you can use the parameter name in the place of the ordinal when setting the parametervalue
e.g. qdf.Parameters("Foo").value = 7832