Updating a field for an entire table via VBA - ms-access

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

Related

VBA SQL Sum Operation in Form

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)

Trying to pass parameters to an MS Access query

I am trying to write a MS Access report based on a query that I can programically put the a date range in using VBA. I set up the query with Between [StartDate] and [EndDate] as the criteria. Then I have the following code on a form:
Private Sub AutoReport1_Click()
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Set qdf = CurrentDb.QueryDefs("MixByRangeA")
qdf.Parameters("StartDate").Value = #10/2/2014#
qdf.Parameters("EndDate").Value = #11/2/2014#
Set rst = qdf.OpenRecordset()
End Sub
Nothing seems to happen. Should the query open and show on the screen? I have tried a few code variations of the above based on my internet searches but nothing works.
Nothing is happening because you're not doing anything with qdf and rst after you set them. I'm not entirely sure what you're trying to accomplish, but:
1. If you want to open a Report whose RecordSource is the results of the Query (with parameters dynamically set), try placing the following in the Report's code module:
Private Sub Report_Open(Cancel As Integer)
Dim db As DAO.Database: Set db = CurrentDb
Dim qdf As DAO.QueryDef
Dim sql As String
Set qdf = db.QueryDefs("MixByRangeA")
sql = qdf.sql
sql = Replace(sql, "[StartDate]", "#10/2/2014#")
sql = Replace(sql, "[EndDate]", "#11/2/2014#")
Me.RecordSource = sql
On Error Resume Next
qdf.Close: Set qdf = Nothing
db.Close: Set db = Nothing
End Sub
And in the Form, use this to open the Report:
Private Sub AutoReport1_Click()
DoCmd.OpenReport "Report1", acViewReport
End Sub
2. If instead you just want to open the Query (with parameters dynamically set), try the following:
Public Sub AutoReport1_Click()
Dim db As DAO.Database: Set db = CurrentDb
Dim qdf As DAO.QueryDef
Dim sql As String
Set qdf = db.QueryDefs("MixByRangeA")
sql = qdf.sql
sql = Replace(sql, "[StartDate]", "#10/2/2014#")
sql = Replace(sql, "[EndDate]", "#11/2/2014#")
qdf.sql = sql
DoCmd.OpenQuery (qdf.Name)
On Error Resume Next
qdf.Close: Set qdf = Nothing
db.Close: Set db = Nothing
End Sub
I don't think it can be done the way simple way you want.
This seems a shame because you've followed what could be considered 'best practise' by using a stored procedure with parameters parameters, rather than constructing dynamic SQL.
The truth is, even if it is good practise generally, you are guilty of going against the natural flow of how the Access Team want you use its software! Looks like you are compelled to dynamically construct a WHERE clause to squirt into the provided method :(
The easy method is to remove the parameters from the query and apply a filter to the report:
Dim StartDate As Date
Dim EndDate As Date
StartDate = #10/2/2014#
EndDate = #11/2/2014#
DoCmd.OpenReport "YourReport", , , "[YourDateField] Between #" & Format(StartDate, "yyyy\/mm\/dd") & "# And #" & Format(EndDate, "yyyy\/mm\/dd") & "#"

Access VBA code to pull all files from a folder and insert them into seperate attachment fields in a table

I have code written to pull a specific file from a folder, insert it into an attachment field (local_attachment) and which creates a new record in table TEMP_attachment. I am trying to pull all the files from a folder and have them each be a new record in the table but I keep running into issues where I either pull all the files and they all go into one record, or it won't pull any. Thank you for your help!!!
Here is my code:
Dim x As Long
Dim strFile As String
Dim db As DAO.Database
Dim rs As DAO.Recordset2
Dim rsA As DAO.Recordset2
Dim fld As DAO.Field2
Dim SQL As String
x = 1
strFile = "C:\dev\test_file2.txt"
SQL = "INSERT INTO TEMP_Attachment (ID) "
SQL = SQL & "VALUES (" & x & ")"
DoCmd.RunSQL SQL
Set db = CurrentDb
Set rs = db.OpenRecordset("TEMP_Attachment")
Set fld = rs("local_attachemnt")
'Navigate through the table
Set rsA = fld.Value
rs.Edit
rsA.AddNew
rsA("FileData").LoadFromFile strFile
rsA.Update
rs.Update
The problems with your code can be fixed my taking a more methodical approach. As I see it, you need to find all the files in the folder, add a record for each one, add an attachment record for the file, read the file data into the new record, and generate a unique key for the parent record.
Rather than try to do everything at once, let's break into pieces and take them in reverse order, so we're dealing with the smallest problems first:
First, let's figure out how we are going to generate a key. The easiest way to do this is to use an Autonumber field. Rather than cook up something fancier, I'm going to assume this is the solution you will use. This will make DoCmd.RunSQL unnecessary and simplify the whole operation.
Second, write a routine which adds one file to one record in the database, and make sure this is working. My suggestion would be to create parameters for a recordset to the main table and a path to the file, like so (I have not tested this, that will be your job. I've added error handlers to help you work out any issues):
Private Sub AddFileAttachment(ByRef rs As DAO.Recordset, ByVal sPath As String)
Dim rsAttachments As DAO.Recordset
On Error Goto EH
With rs
'(this will generate a new Autonumber in the main table)
.AddNew
'this will create a new attachment in the field and add it
Set rsAttachments = .Fields("local_attachemnt").Value
With rsAttachments
.AddNew
.Fields("FileData").LoadFromFile sPath
.Update
.Close
End With
'this is what adds the main record
.Update
End With
EH:
With Err
MsgBox .Number & vbcrlf & .Source & vbCrLf & .Description
End With
FINISH:
If Not rs Is Nothing Then
rs.Close
Set rs = Nothing
End If
If Not rsAttachments Is Nothing Then
rsAttachments.Close
Set rsAttachments = Nothing
End If
End Sub
And call it like so:
Private Sub cmdTest_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
On Error Goto EH
Set db = CurrentDb
Set rs = db.OpenRecordset("TEMP_Attachment")
AddFileAttachment rs, "C:\dev\test_file2.txt"
Goto FINISH
EH:
With Err
MsgBox .Number & vbcrlf & .Source & vbCrLf & .Description
End With
FINISH:
rs.Close
End Sub
Important! Perfect the first routine before moving on. You should test it until you know it works over and over. You should be able to click the button it is attached to 10 times and each time get a new record with the file attached.
Once you know this is working, you are ready to write the main routine that calls it for each file you are attaching. I will not include that here, but would suggest researching the FileSystemObject. You should be able to find a lot of vba examples for how to get all the files in a folder. You would loop through them and call your routine for each file the same way it is called in the test above, passing in the open recordset.

Updating a date record in a table using VBA & cmd button

I'm trying to get a Command Button to update a date on a table. The button is in a separate form. Right now I'm trying:
Private Sub Command13_Click()
Update Master
Set [Last Complete] = Date()
End Sub
"Master" being the table I'm trying to update and "Last Complete" being the specific record.
Access throws an error message with my code, complaining "sub or function isn't properly defined".
I've worked quite a bit with VBA in Excel but not so much with Access.
The problem is that a SQL statement is not valid VBA code.
You can place the statement in a string and use the DAO.Database.Execute method to execute it:
Private Sub Command13_Click()
CurrentDb.Execute "Update Master Set [Last Complete] = Date()"
End Sub
Assuming that UPDATE statement is valid and does what you want, that could be all you need. However, here is another version which demonstrates features you may find useful:
Private Sub Command13_Click()
Dim db As DAO.Database
Dim strUpdate As String
strUpdate = "Update Master Set [Last Complete] = Date()"
Debug.Print strUpdate
Set db = CurrentDb
db.Execute strUpdate, dbFailOnError
Debug.Print db.RecordsAffected & " rows updated"
Set db = Nothing
End Sub

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