VBA SQL Sum Operation in Form - ms-access

In my form i want to use a sum on row SWS from tblKurse used in the query for the form. On a Button Click event i want to sum the values in that row whenever the criterion in my where is met. Problem is i get an invalid argument error whenever i run it. I just cant find my mistake. Maybe someone can help.
Heres the function that i call after the button click event:
Public Function chkSWS() As Integer
Dim db As Database
Dim rst As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT SUM(tblKurse.SWS) As Stunden " _
& "FROM tblKurse " _
& "WHERE tblKurse.Dozent_ID = " & Me.cmbKursDOzent
Debug.Print strSQL
Debug.Print Me.Dozent_ID
Set rst = db.OpenRecordset(strSQL, dbForwardOnly)
chkSWS = rst![Stunden]
Set rst = Nothing
Set db = Nothing
End Function
Error points on the "Set rst" line, so it might been a bad Select statement?
printed SQL Statement:
SELECT SUM(tblKurse.SWS) As Stunden FROM tblKurse WHERE tblKurse.Dozent_ID = 1

Change this line
Set rst = db.OpenRecordset(strSQL, dbForwardOnly)
to this
Set rst = db.OpenRecordset(strSQL, dbOpenSnapshot)

Related

The expression you have entered refers to an object that is closed or doesn't exist error

I am trying to open 2 ADODB recordsets on a button click event like:
Private Sub btn1_Click()
Dim rs As New ADODB.Recordset
Dim rst As New ADODB.Recordset
rs.Open "UPDATE table ITEM = " & Me.ITEM & " where ID = " & ID, CurrentProject.Connection
rs.Close
Set rs = Nothing
rst.Open "Update Table2 set Item2 = " & Me.Item2,CurrentProject.Connection
End Sub
The first error I get is on rs.close where it says:
Operation is not allowed when the object is closed.
I am really confused about this error as I have clearly not closed the record set rs.
But even when I remove rs.close I get:
The expression you have entered refers to an object that is closed or
doesn't exist
on the
rst.Open "Update Table2 set Item2 = " & Me.Item2,CurrentProject.Connection
The first error (on rs.Close) happened because the recordset was never opened.
Your UPDATE (when you included the SET keyword) executed successfully, but an UPDATE does not return records. So the recordset was not opened. Run the following code to clarify the situation ...
Dim rs As New ADODB.Recordset
Dim strUpdate As String
strUpdate = "UPDATE table SET ITEM = " & Me.item & " where ID = " & id
rs.Open strUpdate, CurrentProject.Connection
If rs.State = adStateClosed Then
Debug.Print "can't close recordset because it's already closed"
Else
rs.Close
End If
When you want to execute an UPDATE, you don't need a recordset; you don't even need ADO. You can just do this ...
CurrentDb.Execute strUpdate, dbFailOnError
Regarding your second error, I'm unsure about the cause, but suspect the problem is in building the statement text. Suggest you add this to your code and run it ...
Debug.Print "Update Table2 set Item2 = " & Me.Item2
If that doesn't trigger the same error, copy the statement text from the Immediate window and paste it for testing into SQL View of a new query in the Access query designer. If you're not familiar with the Immediate window, Ctrl+g will take you there.
The .Open method is not for an action query but for a select query.
Since you are evaluating update statements, you should use the .Execute method of the ADODB Connection object rather than the .Open method.

EOF returns true even if i have a populated recordset at the first pos in ADO

Im trying to get rows from the columns in a recordset and then insert those in a table plain and simple.
The recordset is populated and i used .MoveFirst to start at the beginning of the rs, Still i get EOF true at the very start and it jumps out of the do while..
I have a similar function woorking but this one won't woork for some reason.
I can't figureout why... or how to fix this. Anny insight is welcome!
current Code ~
Public Function makeSäljare()
'Create rs
Dim rsData As ADODB.Recordset
Set rsData = New ADODB.Recordset
Dim sql As String
'Select what should be included in the rs.
rsData.Open "SELECT Forhandler, Selger FROM data", _
CurrentProject.Connection, adOpenDynamic, adLockOptimistic
rsData.MoveFirst
MsgBox rsData.GetString
'Manipulate each row of the result column.
Do While Not rsData.EOF
sql = "INSERT INTO säljare (Partner_Namn, Namn ) VALUES ('" & rsData!forhandler & "','" & rsData!Selger & "');"
MsgBox sql
'DoCmd.SetWarnings (False)
DoCmd.RunSQL (sql)
'DoCmd.SetWarnings (True)
rsData.MoveNext
'If rsData.EOF Then Exit Do
Loop
rsData.Close
End Function
It jumps out at Do While Not rsData.EOF..
GetString leaves the recordset at EOF. MoveFirst again before Do While Not rsData.EOF
rsData.MoveFirst
MsgBox rsData.GetString
rsData.MoveFirst ' <-- add this
'Manipulate each row of the result column.
Do While Not rsData.EOF
I didn't try your code, but this logically means that the recordset is empty.
Check carefully if the query you executed on the db is correct.
In Access, use DAO instead of ADO and try this:
Set db = CurrentDb
set rsData = db.OpenRecordset("SELECT Forhandler, Selger FROM data", dbOpenDynaset)

Updating a field for an entire table via VBA

I am trying to add a received date to my table for all the files imported. We receive files and process them up to a week later. I have my import set up and everything but I added a column called "Receive Date". I also added a Date Picker and have it setup in VBA to grab it. I am not sure how to change ALL the records in the table to be the date selected.
Private Sub Command2_Click()
Dim Rec As String
Rec = Text0
End Sub
As you can tell I am just starting this but I do not know which direction I should be going from here. I would assume call the record set and table but I am unsure. Any assistance would be greatly appreciated. Thanks in advance
Sounds like you want the [Receive Date] in all rows of your table set to the date value selected in your Text0 text box. If that is correct, you can execute a SQL UPDATE statement from Command2_Click().
Private Sub Command2_Click()
Dim strUpdate As String
Dim db As DAO.database
Dim qdf As DAO.QueryDef
strUpdate = "PARAMETERS which_date DateTime;" & vbCrLf & _
"UPDATE YourTable" & vbCrLf & _
"Set [Receive Date] = which_date;"
Debug.Print strUpdate
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strUpdate)
qdf.Parameters("which_date") = Me.Text0
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
End Sub

vba code not doing INSERT into database

I am very new to access. I was told that the way to do a database insert in access is with the CurrentDb object (as long as the table is in the same database, and it is in my case.) I made this code, have no errors, but it doesn't do the insert.
Private Sub Add_Delete_Click()
Dim query As String
query = "Insert Into tbl_Inventory_History (InventoryID, Modification_Date, Change)"
query = query & "Values (" & Me.InventoryID & ",#" & Now() & "#," & Me.Quantity & ")"
CurrentDb.Execute query
End Sub
This code is run on a button click in the Inventory form page. I want it to insert any changes made to the inventory on the inventory history page. I made sure the the tbl_Inventory_History does exist and is spelled correctly. What is the issue?
Instead of "gluing together" a SQL statement, you might find it more convenient in this case to add the record by using a Recordset, like this
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("tbl_Inventory_History", dbOpenTable)
rst.AddNew
rst!InventoryID = Me.InventoryID
rst!Modification_Date = Now()
rst!Change = Me.Quantity
rst.Update
rst.Close
Set rst = Nothing

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