MS-Access 2003: Create multiple records from a single form - forms

Can anyone point me to an example of an Access form which can create multiple records (in a single table) based on one form?
To expand: we're recording information about time spent on a project on a given date. We've had a request for a single form that would allow a user to enter data for 5 (or 7) days of a given week on a single form. He/she would pick a week from a calendar control, a project from a listbox, then enter up to 7 numbers for the hours spent that week.
I did check questions 5294128, which doesn't seem applicable, and question 8070706, which seems to imply that this can only be done in VBA (not using the GUI). Any alternatives?
Thanks.

Something on these lines should suit. This is an unbound form with a subform.
You can get the form type from the form wizard
To work properly, you will need a little code, say:
Private Sub cmdGo_Click()
Dim rs As DAO.Recordset
Dim sSQL As String
Dim sSDate As String
Dim sEDate As String
sSDate = "#" & Format(Me.txtStartDate, "yyyy/mm/dd") & "#"
sEDate = "#" & Format(Me.txtStartDate + Me.txtNoDays, "yyyy/mm/dd") & "#"
sSQL = "SELECT * FROM MyTable WHERE DataDate Between " & sSDate _
& " AND " & sEDate
Set rs = CurrentDb.OpenRecordset(sSQL)
If rs.RecordCount < Me.txtNoDays Then
AddRecords sSDate, sEDate
End If
Me.DataSubform.Form.RecordSource = sSQL
End Sub
Sub AddRecords(sSDate, sEDate)
''Uses counter table with integers from 0 to
''highest required number
''Another useful table is a calendat table, which would
''save some work here.
sSQL = "INSERT INTO MyTable (DataDate) " _
& "SELECT AddDate FROM " _
& "(SELECT " & sSDate _
& " + [counter.ID] AS AddDate " _
& "FROM [Counter] " _
& "WHERE " & sSDate _
& "+ [counter.ID] Between " & sSDate _
& " And " & sEDate & ") a " _
& "WHERE AddDate NOT In (SELECT DataDate FROM MyTable)"
CurrentDb.Execute sSQL, dbFailOnError
End Sub

Related

Ms Access Form - How to completely filter text using search button

`Option Compare Database
Option Explicit
Dim argcount As Integer
Dim mysql As String, msg As String, mysource As String, mycriteria As String, mysource1 As String, mysql1 As String
Private Sub AddtoWhere(FieldValue As Variant, FieldName As String, mycriteria As String, argcount As Integer)
' Create criteria for WHERE clause.
If FieldValue <> "" Then
' Add "and" if other criterion exists.
If argcount > 0 Then
mycriteria = mycriteria & " and "
End If
' Append criterion to existing criteria.
' Enclose FieldValue and asterisk in quotation marks.
mycriteria = (mycriteria & FieldName & " Like " & Chr(34) & FieldValue & Chr(42) & Chr(34))
' Increase argument count.
argcount = argcount + 1
End If
End Sub
Private Sub Search_Click()
Dim Search As String
here:
argcount = 0
' Initialize SELECT statement.
mysql = "SELECT * FROM tbltab WHERE "
mycriteria = ""
mysql1 = "SELECT * FROM tblTemp WHERE "
mycriteria = ""
' Use values entered in text boxes in form header to create criteria for WHERE clause.
AddtoWhere cboProduct, "ABC1", mycriteria, argcount
AddtoWhere cboSource, "ABC2", mycriteria, argcount
AddtoWhere cboPType, "ABC3", mycriteria, argcount
'If no criterion specifed, stop the search.
'you'll be glad you did if there are thousands of Persons maybe.
If mycriteria = "" Then
mycriteria = True
End If
' Create SELECT statement.
mysource = mysql & mycriteria
mysource1 = mysql1 & mycriteria
Dim strval As String
'set the recordsource of the subform to the resultset
Me!sfrmCap.Form.RecordSource = mysource
Me!sfrmCapTemp.Form.RecordSource = mysource1
Exit_cmdsearch_Click:
Exit Sub
Err_cmdsearch_Click:
DoCmd.Hourglass False
DoCmd.Echo True
MsgBox Err.Description & " Person Search Command Cancelled", vbInformation, "Person Search Command Cancelled"
Resume Exit_cmdsearch_Click
End Sub
`I have a form in which there are 2 subform. I have a search button which when click search record using combo box values but in one combo box it display just related record not the complete search.
Can anyone help me in this.
Thank you.
In AddtoWhere() you assemble your WHERE clause, adding new conditions like this:
mycriteria = (mycriteria & FieldName & " Like " & Chr(34) & FieldValue & Chr(42) & Chr(34))
If you are unsure about what this actually does, you can put a breakpoint on the line (double clicking in the margin in front of the line) and see for yourself while executing the program.
If you do, you'll find out that a new condition like this will be added:
Source Like "Pre 2017 Source1*"
The * (encoded with Chr(42) in your code) acts as a joker matching any characters, so this condition returns everything that begins with Pre 2017 Source1 - as you can see in the search results.
If you do not want this behaviour, just remove the star from the SQL code and only exact matches will be returned.
Btw.: You should improve that code line like this:
mycriteria = mycriteria & FieldName & " LIKE '" & Replace(FieldValue, "'", "''") & "'"
This removes the unnecessary use of Chr(), replaces double quotes by single quotes as SQL string delimiters as it is recommended, and enables the code to handle values that contain quotes, which would otherwise result in a runtime error.

Me.Filter Access Code Syntax

I am trying to filter a form that emails only the current record. I have tried to do the me.filter command but cannot seem to get the syntax correct. I have provided the code below. The Current Date field is a date field and the Discover, Tail, and FleetID fields are text fields. I was told to put in the me.filter code the primary keys of the table that the form is linked to so the pdf that is produced does not print all the records linked to the form. Please let me know if you see something with my code. Thanks in advance :)
On Error GoTo errhandle
Me.Filter = "CurrentDate= #" & Me!CurrentDate & "#" And "Discover= '" & Me!Discover & "'" And "Tail= '" & Me!Tail & "'" And "FleetID= '" & Me!FleetID & "'"
Me.FilterOn = True
DoCmd.SendObject acSendForm, "frmETIC", acFormatPDF, "email address", "", "", "Recovery Report", "Attached is the submitted Recovery Report"
exitErr:
Exit Sub
errhandle:
If Err.Number <> 2501 Then
MsgBox ("Email cancelled!")
End If
Resume exitEr
All those And-operators are meant to be for the filtering, so they need to be inside the filter-string. Otherwise they are used as boolean operators in VBA, which will cause a type mismatch error when used on strings.
Another issues with your code is the date in the filter string. You will not get the desired result unless the date is formatted properly for use in a SQL criteria.
Replace the line Me.Filter = ... with the following to fix both problems.
Me.Filter = "CurrentDate= #" & Format(Me!CurrentDate, "yyyy\-mm\-dd") & "# AND Discover= '" & Me!Discover & "' AND Tail= '" & Me!Tail & "' AND FleetID= '" & Me!FleetID & "'"
If this filter string does not return the expected results, put a Debug.Print Me.Filter on the next line. This will print the actual filter string into the Immediate Window and allow you to see if it contains the expected values. For further debugging create a new Query in Access, switch to SQL View and enter SELECT * FROM yourTable WHERE filterStringOutput as SQL. Run the query. If it does not return the expected records, remove the criteria one by one to find the one that is causing problems.

Date function in access vba outputting time

I am trying to update a date field in a table to the current date when a button is clicked on a form and that given field is empty. However, when the field is updated, the output is the time 12:00:05, not a date at all. When year(date) is used instead, 7/7/1905 is the output. I am not sure why these values are my outputs. Here is my code:
Dim ctl As Control
Set ctl = [Forms]![frm1]![subfrm1].[Form]![CloseDate]
If IsNull(ctl) Then
DoCmd.SetWarnings False
DoCmd.RunSQL "Update tbl1 SET [CloseItem] = ""YES"" WHERE [ID] = " & [Forms]![frm1]![ID].Value & " AND [Item#] = " & [Forms]![frm1]![subfrm1].[Form]![ItemID].Value
DoCmd.RunSQL "Update tbl1 SET [CloseDate] = " & Date & " WHERE [ID] = " & [Forms]![frm1]![ID].Value & " AND [ItemID] = " & [Forms]![frm1]![subfrm1].[Form]![ItemID].Value
' Output is 12:00:05
' OR DoCmd.RunSQL "Update tbl1 SET [CloseDate] = " & Year(Date) & " WHERE [ID] = " & [Forms]![frm1]![ID].Value & " AND [ItemID] = " & [Forms]![frm1]![subfrm1].[Form]![ItemID].Value
DoCmd.RefreshRecord
' Output is 7/7/1905
End If
How can I get it to output the correct date?
Examine the string your code builds for this segment of the UPDATE statement. (This is an example copied from the Access Immediate window. You can go there with Ctrl+g)
? "Update tbl1 SET [CloseDate] = " & Date & " WHERE [ID] = "
Update tbl1 SET [CloseDate] = 2/16/2015 WHERE [ID] =
The db engine does not see 2/16/2015 as a Date/Time value. Instead, it treats that as 2 divided by 16 divided by 2015. And the resulting number, when expressed as a Date/Time value, gives you this ...
? Format(2/16/2015, "yyyy-m-d hh:nn:ss")
1899-12-30 00:00:05
You can signal the db engine that 2/16/2015 is a Date/Time value by enclosing it in # delimiters like this: #2/16/2015#
However, since the db engine understands the Date() function, you can use that function name directly in your UPDATE statement and not bother about concatenating in a value with proper delimiters.
Dim strUpdate As String
strUpdate = "Update tbl1 SET [CloseDate] = Date() WHERE [ID] = " & _
[Forms]![frm1]![ID].Value & " AND [ItemID] = " & _
[Forms]![frm1]![subfrm1].[Form]![ItemID].Value
Debug.Print strUpdate
CurrentDb.Execute strUpdate, dbFailOnError

MS Chart Control showing blank when rowsource contains a WHERE Clause

First time poster and new to MS ACCESS. I am using MS ACCESS 2002-2003 database format.
I have a Mainform in which I have a tabbed control. In one of the tabs, I have a subform where I put another tabbed control. In one of those tabs, I have a combobox that has a list of categories and I am trying to pass that value to a MS Chart control using VBA. The chart will update (it will show all categories) as long as there is no WHERE clause . If I remove the variable from the WHERE clause and type a VALUE in, it still does not work. When I run Debug.Print strSQLPIE. The strSQLPIE value shows the SQL statement and the WHERE clause correctly. However, Chart keeps showing up as blank. If i copy that SQL statement and put it in a new query, the query runs fine.
I have netted the issue down to the WHERE clause of the SQL statement in the ROWSOURCE property of the chart control. What am i missing?
Here is the code:
Dim DB As Database
Dim rst As Recordset
Dim strSQLSB As String ' subform datasheet sql
Dim strSQLPIE As String ' chart control sql
Dim SelCatStr As String ' combobox for categories
Dim SelYrStr As String ' not being used for now
Dim SelYrMtStr As String ' not being used for now
SelCatStr = Me.PIEChart.Value ' combobox selected value
'SelYrStr = Me.SelectYear.Value ' not being used for now
'SelYrMtStr = Me.SelectYearMonth.Value ' not being used for now
strSQLSB = "SELECT UNIONMASTER.ByMonth, UNIONMASTER.Category, UNIONMASTER.Category1, UNIONMASTER.AdjustedAmount " & _
"FROM UNIONMASTER " & _
"WHERE UNIONMASTER.Category1= '" & SelCatStr & "';" THIS UPDATES THE DATASHEET IN ANOTHER SUBFORM IN THE SAME TAB CORRECTLY ON CHANGE OF COMBOBOX.
strSQLPIE = "SELECT UNIONMASTER.Category1, Sum(UNIONMASTER.AdjustedAmount) AS TotalSpent " & _
"FROM UNIONMASTER " & _
"WHERE UNIONMASTER.Category1= '" & Me.PIEChart.Value & "';"
I TRIED USING SelCatStr and Me.PIEChart.Value in the WHERE CLAUSE and it still down not work. I even tried typing in a value and it still does not work. The debug window shows the SQL correctly and the where clause correctly, but the chart shows up as blank as long as the WHERE clause is there.
Me.PIESubform.Form.RecordSource = strSQLSB
Me.[PIESubform].Form.Requery
Debug.Print strSQLPIE
Me.[CatChart].RowSource = strSQLPIE
Me.[CatChart].Requery
I think the problem has to do with the WHERE clause in the rowsource setting of the CHART. As i said, when I remove the where clause, the chart shows correctly for all categories, the moment i stick the WHERE clause, with a VALUE or with a variable, it shows blank.
The chart works if i use this:
strSQLPIE = "SELECT UNIONMASTER.Category1, Sum(UNIONMASTER.AdjustedAmount) AS TotalSpent " & _
"FROM UNIONMASTER " & _
"GROUP BY UNIONMASTER.Category1 ;"
Me.CatChart.RowSource = strSQLPIE
Me.CatChart.Requery
Any ideas?
You may missing 'GROUP BY' clause in your query. Your query should be like this.
strSQLPIE = "SELECT UNIONMASTER.Category1, " &_
"Sum(UNIONMASTER.AdjustedAmount) AS TotalSpent " & _
"FROM UNIONMASTER " & _
"WHERE UNIONMASTER.Category1= '" & Me.PIEChart.Value & "';" &_
"GROUP BY UNIONMASTER.Category1 ;"

Insert Into Access Table Form

I have a table I created and its purpose is to house a database of queries i have created over the years, I created a corresponding form to insert all the information but I am having trouble getting the code to work.
Private Sub cmd_go_Click()
Dim insertstring As String
insertstring = "INSERT INTO KWTable (KW, Source, Code) VALUES (" & text_key.Value & "," & combo_source.Value & "," & text_code.Text & ");"
DoCmd.RunSQL insertstring
End Sub
The three columns on the destination table are KW, Source, and Code the values being inserting into them are text_key (which are keywords that I type in so i can search them later when i need to reference certain things), combo_source.Value (which is a combo box with the list of databases where these codes and queries are saved, which i will select the right one when inserting into the table) and text_code ( which is the actual code itself of the query)
The code is supposed to insert the keywords (text) the source (combobox listing) and the code (text) into the KWTable. But when I click the add record button I get a "Runtime Error 424: Object Required" Error box and it has the whole insertstring line highlighted. I cannot troubleshoot where the error is. Any thoughts?
Option 1
As Remou said, you have no quotes around your text. I've added some single quotes around each of your fields and added some line breaks for easier reading. Does that work?
Private Sub cmd_go_Click()
Dim insertstring As String
insertstring = "INSERT INTO KWTable (KW, Source, Code) VALUES ('" & _
text_key.Value & "','" & _
combo_source.Value & "','" & _
text_code & "');"
DoCmd.RunSQL insertstring
End Sub
Option 2
I think this will handle storing single and double quotes in your table:
Private Sub cmd_go_Click()
Dim rst As recordset
Set rst = CurrentDb.OpenRecordset("KWTable ")
With rst
.addnew
.fields("KW")=text_key.Value
.fields("Source")=combo_source.Value
.fields("Code")=text_code
.update
End with
End sub