How to retrieve a count of all records where a Date field is within the next year, and store it in a variable? - date

I am fairly new to MS Access, but have a decent understanding of databases, with some knowledge of SQL.
I am creating a database in Access. On a main form that users will see first, I need to display a count of all records from my Case table, which have a StatuteOfLimitation date that is within the next year.
My goal was to create a label describing the information, with a button below it. The button will open a report of all of the records (this part is working fine), and I wanted the caption for the button to display the total count of how many records meet the criteria.
The only way I can think to do it, is to retrieve the count and store it into a variable. From there, I should be able to set the caption to the variable value.
I have seen a few methods of retrieving a count and storing it in a variable, but all that I found only stored a count of EVERY record, without filtering for the date range.
This was the best that I could think of, but it is not working:
Private Sub Form_Load()
Dim oneYearFromToday As TempVars
SET TempVars!oneYearFromToday = (SELECT COUNT(StatuteOfLimitation) FROM Case
WHERE StatuteOfLimitation <= DateAdd("yyyy", 1, Date());
End Sub

DCount() provides a simple approach for "How to retrieve a count of all records where a Date field is within the next year"
Dim lngCount As Long
lngCount = DCount("*", "Case", "[StatuteOfLimitation] <= DateAdd('yyyy', 1, Date())")
Then you can use that count in your command button's Caption property. Say the button is named cmdOpenReport ...
Me!cmdOpenReport.Caption = "Report " & lngCount & " cases"
If you want the count in a TempVar instead of a regular Long variable, declare it As TempVar (just one) instead of As TempVars (a collection). And when you assign the value to it, don't use Set.
Dim oneYearFromToday As TempVar
TempVars!oneYearFromToday = DCount("*", "Case", "[StatuteOfLimitation] <= DateAdd('yyyy', 1, Date())")

I probably wouldn't use a tempvar to store your variable. you can try something like below using the DAO.
Private sub Form_Load()
dim rst as dao.recordset
dim strSQL as string
'Creates query string
strsql = "SELECT Count(StatueOfLimitation) as RecordCount " & _
"FROM Case " & _
"WHERE (((StatueOfLimitation) <= DateAdd('yyyy',1,date())));"
'Opens the query string into a recordset
set rst = currentdb.openrecordset(strsql)
'Change Labelnamehere isnto the name of the label control on your form
'Change what ever saying you want here to something you want the label to display
me.labelnamehere.caption = "What ever saying you want here " & rst![RecordCount] 'Don't need a variable storage is you can use the result here
rst.close 'closes recordset
set rst = nothing 'Clears memory
EndCode: 'Ensures clean up is successful
If not rst is nothing then
rst.close
set rst = nothing
end if
end sub
If this doesn't work for you, please let me know and I'll do some more digging.

I'm not able to comment on HansUp's answer, but to change a label caption in VBA you need to open the form in Design view. It's not something I typically do, my personal preference is to use an unbound text box with labels that don't change, but I have done it in one database to update the time/date and user for the last email sent.
The code would look like this:
DoCmd.OpenForm "yourformname", acDesign, , , , acHidden
Forms![yourformname]![yourlabelname].Caption = "There are " & TempVars!onYearFromToday & " cases to view."
DoCmd.Close acForm, "yourformname", acSaveYes
DoCmd.OpenForm "yourformname", acNormal

It's a bad idea to use a button for info display. That's not the purpose of a button.
Use a textbox and set its ControlSource:
=DCount("*","[Case]","[StatuteOfLimitation]<=DateAdd("yyyy",1,Date()))
It will fill by itself, and the button is free to open the report at any time.

Related

Why is Access form giving me the error message "A column number has been specified more than once in the order list"? The related queries open fine

I'm working on an Access database with a SQL Server back end. Some times when I open a particular form, I get an Error 3146 "Column has been specified more than once in the order by list."
There are several possible queries that might feed into this form but I checked and ran them all individually and they run fine, so it's something in the form but I'm not sure. Below is a screen shot of the Data Properties window. My hypothesis is that "Order By" property (which I did not populate manually) is not being cleared out when the form closes, and thus when the form is re-opened, that in effect puts in the same columns twice.
I can temporarily solve the problem by opening up the form and clearing those Filter and Order By fields. That solves it for a while but intermittently it will happen again so there's probably one other thing I'm overlooking. I put in code in the Form close event to set the orderby="" but even that doesn't totally solve it.
Here is the code that opens the form from the main menu (frmProdSched is the form in question)
Private Function OpenProdSched(RunQuery, RunCaption)
DoCmd.OpenForm "frmProdSched", , RunQuery, "", , acNormal
Forms!frmProdSched.Caption = RunCaption
gScheduleRptQry = RunQuery
Me.Refresh
End Function
and then the code that is in the Form_Current event
Private Sub Form_Current()
On Error Resume Next
Dim strForm As String
Dim strForm1 As String
Dim strWhere As String
strForm = "frmSubmittalStatus"
strForm1 = "frmProdSched"
strWhere = "StatusJobno = " & Me.JOBNO & ""
If IsLoaded(strForm) Then
If Forms(strForm).Filter = strWhere Then
Forms(strForm1).SetFocus
Else
DoCmd.Close acForm, strForm
DoCmd.OpenForm FormName:=strForm, WhereCondition:=strWhere
Forms(strForm1).SetFocus
End If
End If
End Sub
I tried adding this code to the Form Close event and it seemed to work most of the time but it still intermittently happens
Private Sub Form_Close()
Me.Filter = ""
Me.OrderBy = ""
End Sub
I'm not sure what to check next. Any ideas?

Create Access reports from Form and save as PDF

Im currently using an Access database to create alot of reports - the report is made using a Query as a source, in the Query i use a Form as criteria so that the open page in the Form is the data used in the report.
Then I save the report as a PDF and click in the form to run the next set of data.
That is very time consuming when i have over 500 reports to make. So is there a way to make a function, a VBA or macro to run through all pages in the form and save each report as a PDF?
My form is named NorwF, the query is NorwQ and the report is NorwRap
I hope that makes sense and that there is a faster way to make this projekt run smoothly.
If you place a button on the form, this code behind should work:
Dim rst As DAO.Recordset
Dim strReport As String
Dim strReportFile As String
strReport = "NorwRap"
'Set rst = Me.RecordsetClone
Set rst = CurrentDB.OpenRecordSet("NorwQ") 'use the query
Do While rst.EOF = False
strReportFile = rst!ID & ".pdf" ' give report name based on field name
DoCmd.OpenReport strReport,acViewPreview , , "id = " & rst!ID
DoCmd.OutputTo acOutputReport, strReport, acFormatPDF, strOutFile
DoCmd.Close acReport, strReport
rst.MoveNext
Loop

update through vba new record, currently opened in a form

I have a question regarding updating new record through VBA.
First - the assumptions.
I've made a form called "assortment", that displays a set of records and a sobreport that shows related invntory. I've put the button on it: "Add new record". This opens the second form "inventory_details" that is intended to enter and view the inventory spcific data. That inventory is of that specific assortment type. So - I've passed the assortment_id to the inventory_details form through the DoCmd.OpenForm like:
DoCmd.OpenForm stFormName, , , , acFormAdd, , Me.assortment_id
The data source of the "inventory_details" form is a query that contains the assortment table joined to the inventory table by the inventory_id. What is the best way to add this id passed by an OpenArgs to the currently opened new record and refresh the form to show related assortment data?
I was trying to do this like:
Private Sub Form_Open(Cancel As Integer)
Dim assortmentId As Integer
If (Not IsNull(Me.OpenArgs)) Then
assortmentId = Me.OpenArgs()
Set rst = Me.Recordset
rst.Edit
rst.assortment_id_assortment = assortmentId
Me.Requery
End If
End Sub
but it gives me an error "3021 " No current record"...
Here are some suggestions,
. Make sure you define the variable rst
. Check for EOF Condition to make sure your recordset contains rows
If rst.EOF Then
MsgBox "The Recordset is empty."
End If
. Why clone an MS-Access recordset?

Creating a 'calendar matrix' in Access

I’m trying to create either a report or form that displays data in essentially a “calendar” form.
I have a course query that is (simplified) as “Course name”; “course days”; “course times”---
Course; Days; Times
PSY 1; MW; 8A-9A
SOC 150; M; 8A-11A
ANTH 2; Tu; 8A-9A
ANTH 199; MW; 8A-9A
In Access, I’m trying to create a form based on the query that would give me a matrix of the following:
Columns: Times in hour increments
Rows: Days of week
So, for example, with the above data, it would appear like this:
Edit: Yargh, I can't submit an image unfortunately. So, here is a link to a "course schedule" that is essentially what I'm trying to do: Schedule
I have no idea where to start with this. Any tips (or links)?
Edit:
One idea I have is to create a form with a field for every possible cell in the matrix (so, for example, there would be one "Monday, 8-9A" field--and that field would be a filter on the query that ONLY displays results where "day" contains "M" and BeginTime or EndTime or between 8A and 9A). Unfortunately, I'm not sure how to do that.
You can do something close to what you seem to want as an Access form, but it's not easy. This screen capture displays your sample data in a Datasheet View form whose record source is an ADO disconnected recordset. It uses conditional formatting to set the text box background color when the text box value is not Null. Your picture suggested a different color for each Course, but I didn't want to deal with that when more than one Course can be scheduled in the same time block ... my way was simpler for me to cope with. :-)
The code to create and load the disconnected recordset is included below as GetRecordset(). The form's open event sets its recordset to GetRecordset().
Private Sub Form_Open(Cancel As Integer)
Set Me.Recordset = GetRecordset
End Sub
Note I stored your sample data differently. Here is my Class_sessions table:
Course day_of_week start_time end_time
------ ----------- ---------- -----------
PSY 1 2 8:00:00 AM 9:00:00 AM
PSY 1 4 8:00:00 AM 9:00:00 AM
SOC 150 2 8:00:00 AM 11:00:00 AM
ANTH 2 3 8:00:00 AM 9:00:00 AM
ANTH 199 2 8:00:00 AM 9:00:00 AM
ANTH 199 4 8:00:00 AM 9:00:00 AM
This is the function to create the disconnected recordset which is the critical piece for this approach. I developed this using early binding which requires a reference for "Microsoft ActiveX Data Objects [version] Library"; I used version 2.8. For production use, I would convert the code to use late binding and discard the reference. I left it as early binding so that you may use Intellisense to help you understand how it works.
Public Function GetRecordset() As Object
Dim rsAdo As ADODB.Recordset
Dim fld As ADODB.Field
Dim db As DAO.Database
Dim dteTime As Date
Dim i As Long
Dim qdf As DAO.QueryDef
Dim rsDao As DAO.Recordset
Dim strSql As String
Set rsAdo = New ADODB.Recordset
With rsAdo
.Fields.Append "start_time", adDate, , adFldKeyColumn
For i = 2 To 6
.Fields.Append WeekdayName(i), adLongVarChar, -1, adFldMayBeNull
Next
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.LockType = adLockPessimistic
.Open
End With
strSql = "PARAMETERS block_start DateTime;" & vbCrLf & _
"SELECT day_of_week, Course, start_time, end_time" & vbCrLf & _
"FROM Class_sessions" & vbCrLf & _
"WHERE [block_start] BETWEEN start_time AND end_time" & vbCrLf & _
"ORDER BY day_of_week, Course;"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strSql)
dteTime = #7:00:00 AM#
Do While dteTime < #6:00:00 PM#
'Debug.Print "Block start: " & dteTime
rsAdo.AddNew
rsAdo!start_time = dteTime
rsAdo.Update
qdf.Parameters("block_start") = dteTime
Set rsDao = qdf.OpenRecordset(dbOpenSnapshot)
Do While Not rsDao.EOF
'Debug.Print WeekdayName(rsDao!day_of_week), rsDao!Course
rsAdo.Fields(WeekdayName(rsDao!day_of_week)) = _
rsAdo.Fields(WeekdayName(rsDao!day_of_week)) & _
rsDao!Course & vbCrLf
rsAdo.Update
rsDao.MoveNext
Loop
dteTime = DateAdd("h", 1, dteTime)
Loop
rsDao.Close
Set rsDao = Nothing
qdf.Close
Set qdf = Nothing
Set GetRecordset = rsAdo
End Function
Actually, if you look at the following video of mine, you can see a calendar created in Access that runs inside of a browser with the new Access Web publishing feature.
http://www.youtube.com/watch?v=AU4mH0jPntI
So, all you really need to do here is format a form with text boxes and setup some code to fill them. VBA or even the above video shows this is quite easy for Access.
I doubt that you will find an easy solution for this problem in Access forms or reports.
The issue is that you need to format different cells differently, and that cells can span multiple rows and have to be merged.
If I were you, I would go in either of these 2 directions:
Drive Excel from Access, because you can format and merge cells independently
Use the Web Browser Control to display HTML that you construct yourself using tables, or a more high-level library like FullCalendar
I would be partial to tryingthe Web Browser and find the right library that can properly format the data.
I know this post is quite old, but I had the same requirement but I got round it by doing the following:
I created a module that would write HTML code (as a text file) to produce the data using a table.
I used the colspan feature of tables to enable me to dynamically produce the view I needed.
The HTML file was created on the Form_Open event and by pointing the webbrowser control to the HTML file the view shows the latest data.
A css file is used to handle the visual display of the HTML file so that it looks similar to the Access forms already in use.
If anyone is interested I can post some code to further illustrate.

Enable Save button on different tabs when a form opens

I have a tab control on a form, and a couple different tabs have save buttons on them. Once the user saves data (via SQL statements in VBA), I set the .enabled = false so that they cannot use this button again until moving to a brand new record (which is a button click on the overall form).
so when my form open i was going to reference a sub that enabled all these save buttons because the open event would mean new record. though i get an error that says it either does not exist, or is closed.
any ideas?
thanks
EDIT:
Sub Example()
error handling
Dim db as dao.database
dim rs as dao.recordset
dim sql as string
SQL = "INSERT INTO tblMain (Name, Address, CITY) VALUES ("
if not isnull (me.name) then
sql = sql & """" & me.name & ""","
else
sql = sql & " NULL,"
end if
if not insull(me.adress) then
sql = sql & " """ & me.address & ""","
else
sql = sql & " NULL,"
end if
if not isnull(me.city) then
sql = sql & " """ & me.city & ""","
else
sql = sql & " NULL,"
end if
'debug.print(sql)
set db = currentdb
db.execute (sql)
MsgBox "Changes were successfully saved"
me.MyTabCtl.Pages.Item("SecondPage").setfocus
me.cmdSaveInfo.enabled = false
and then on then the cmdSave needs to get re enabled on a new record (which by the way, this form is unbound), so it all happens when the form is re-opened. I tried this:
Sub Form_Open()
me.cmdSaveInfo.enabled = true
End Sub
and this is where I get the error stated above. So this is also not the tab that has focus when the form opens. Is that why I get this error? I cannot enable or disable a control when the tab is not showing?
You cannot use the form open event to manipulate controls, they have not been initiated at that stage. Use the form load event.
It should never be necessary to set focus to a tab, or even to reference it when working with a control. You will notice that controls must have names unique to the form, and adding a tab does not change this.
I suggest you set some form-level variables: booBtn_1_enabled as Boolean, booBtn_2_enabled as Boolean. Set these to T or F as needed; obviously, all T when the form is opened. Pick a form event (possibly the Current event, but preferably one that is triggered less often) that reviews these variables and sets the controls accordingly:
Me.btnBtn_1.Enabled = booBtn_1_enabled
Me.Repaint
Something like that, but obviously Me.btnBtn_1 may need a more complicated reference.