473,549 Members | 2,726 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Open a subform on a record closest to today's date

10 New Member
Hi,

I'm trying to get MS Access to automatically move the cursor to the record near today's date within a subform in a project management database (frmvw_mileston es). The Main form (FRM_staff_proj ect) has the project information and it includes a subform (frmvw_mileston es) that has details about the important milestones within certain projects. The subform shows all the milestones for the fiscal year for the staff member. I want to move the cursor down within the form so that the staff member sees his/her current milestones upon opening the form instead of having to scroll down.

The following code almost works:
Expand|Select|Wrap|Line Numbers
  1. Private Sub Form_Load()
  2.     Dim db As DAO.Database
  3.     Dim rst As DAO.Recordset
  4.     Dim strSQL As String
  5.     Dim TheDate As Date
  6.  
  7.     Set db = CurrentDb
  8.     strSQL = "SELECT max(Milestone_Date) as Dte " & _
  9.              "FROM qryvw_milestones " & _
  10.              "WHERE Milestone_Date<=Now()"
  11.     Set rst = db.OpenRecordset(strSQL)
  12.     TheDate = rst.Fields(0)
  13.     Me.Milestone_Date.SetFocus
  14.     DoCmd.FindRecord TheDate
  15.     Me.Milestone_Date.SetFocus
  16.  
  17. End Sub
---------------
However, I need to modify this code so that it selects the maximum Milestone_Date for that staff member based on his/her id (ID_staff) instead of the maximum Milestone_Date for all staff members. I tried modifying the SELECT statement to following but it generates errors:
Expand|Select|Wrap|Line Numbers
  1. strSQL = "SELECT max(Milestone_Date) as Dte " & _
  2.          "FROM qryvw_milestones " & _
  3.          "WHERE (Milestone_Date<=now() " & _
  4.          "AND (tbl_pria_projects.ID_staff)=[Forms]![FRM_staff_projects]![ID_staff])"
Any help would be appreciated. Attached are pictures of the main form (FRM_staff_proj ects) and the underlying query (qryvw_mileston es)


Attached Images
File Type: jpg 2018-05-01_10-46-45 swoop project form.jpg (53.7 KB, 346 views)
File Type: jpg qryvw_milestones.jpg (57.0 KB, 360 views)
May 1 '18 #1
12 1844
twinnyfo
3,653 Recognized Expert Moderator Specialist
Karen,

Welcome to Bytes!

First, as an administrative note, when posting code to this forum, please use the code tags in your text editor, as it is easier for users to see your code and debug it. I've done so above, as well as adjusted some formatting so things don't have to slide so far to the right....

Second, I must assume that the field tbl_pria_projec ts.ID_staff is part of the query qryvw_milestone s. If not, then this is definitely part of your problem. I may presume that it is not, since you are declaring it explicitly with the table name and the field name. If it was part of your Query, it would probably simply be ID_Staff. This should be corrected by adding the ID_Staff as an output field of your Query (you will have to join the Staff table to your Query).

Third, an additional problem has to do with the syntax of your SQL statement. You must use the value from your form within the SQL statement, and not just list it within the WHERE clause. Additionally, it is often better to determine what it is you are looking for first, assign it to a variable, and then use that variable within your SQL WHERE clause. Here is what I am talking about [assuming all else remains the same in your code]:

Expand|Select|Wrap|Line Numbers
  1.     Dim lngStaff As Long
  2.     lngStaff = [FRM_staff_projects]![ID_staff]
  3.  
  4.     [all the rest of your code]
  5.  
  6.     strSQL = "SELECT max(Milestone_Date) as Dte " & _
  7.         "FROM qryvw_milestones " & _
  8.         "WHERE ((Milestone_Date<=now()) " & _
  9.         "AND (ID_staff = " & lngStaff & "))"
  10.  
  11.     [finish your code]
  12.  
  13.  
Notice 1) that we are concatenating the value of lngStaff (I am assuming an autonumbering index here) into the SQL statement and 2) that this method can significantly clean up your Code.

Let me know if you have any additional questions.

Hope this hepps!
May 1 '18 #2
Karen20785
10 New Member
Thanks twinnyfo!

Yes, field tbl_pria_projec ts.ID_staff is part of the query qryvw_milestone s. Your suggested coding worked with one slight modification:


Expand|Select|Wrap|Line Numbers
  1. Dim db As DAO.Database
  2.     Dim rst As DAO.Recordset
  3.     Dim strSQL As String
  4.     Dim TheDate As Date
  5.     Dim lngStaff As Long
  6.  
  7.     lngStaff = Me.ID_staff
  8.     Set db = CurrentDb
  9.  
  10.     strSQL = "SELECT max(Milestone_Date) as Dte " & _
  11.         "FROM qryvw_milestones " & _
  12.         "WHERE ((Milestone_Date<=now()) " & _
  13.         "AND (ID_staff = " & lngStaff & "))"
  14.     Set rst = db.OpenRecordset(strSQL)
  15.     TheDate = rst.Fields(0)
  16.     Me.Milestone_Date.SetFocus
  17.     DoCmd.FindRecord TheDate
  18.     Me.Milestone_Date.SetFocus
  19.  
However, I encountered an unexpected problem. A few of our staff members do not have any milestones. This results in a runtime error when they open the form since they don't have any records to show in the subform frmvw_milestone s. Is there anyway to hide the subform or show a blank record when this occurs?
May 2 '18 #3
twinnyfo
3,653 Recognized Expert Moderator Specialist
Is there anyway to hide the subform or show a blank record when this occurs?
This is actually quite easy. Since you know the person, using ID_Staff, before you go to the particular record, check to see if the user has any Milestones in the recordset in question. Then, a simple If ... Then ... Else. You have the Then part; the Else would be something like this:

Expand|Select|Wrap|Line Numbers
  1. With Me.frmvw_milestones.Form
  2.     .Filter = "ID_Staff = 0"
  3.     .FilterOn = True
  4. End With
Hope this hepps!
May 2 '18 #4
Karen20785
10 New Member
Thanks Twinnyfo,

Unfortunately, it still gives me "Run-time error '2427': You entered an expression that has no value" message whenever the user has no milestones.

Below is a copy of coding (for some reason I had to replace Me.frmvw_milest ones.Form with Me!formvw_miles tones.Form)


Expand|Select|Wrap|Line Numbers
  1. Dim db As DAO.Database
  2.     Dim rst As DAO.Recordset
  3.     Dim strSQL As String
  4.     Dim TheDate As Date
  5.      Dim lngStaff As Long
  6.  
  7.     Set db = CurrentDb
  8.  
  9.     If Me.ID_staff <> 0 Then
  10.     lngStaff = Me.ID_staff
  11.     strSQL = "SELECT max(Milestone_Date) as Dte " & _
  12.         "FROM qryvw_milestones " & _
  13.         "WHERE ((Milestone_Date<=now()) " & _
  14.         "AND (ID_staff = " & lngStaff & "))"
  15.     Set rst = db.OpenRecordset(strSQL)
  16.     TheDate = rst.Fields(0)
  17.     Me.Milestone_Date.SetFocus
  18.     DoCmd.FindRecord TheDate
  19.     Me.Milestone_Date.SetFocus
  20.  
  21.  
  22.   Else
  23.   With Me!frmvw_milestones.Form
  24.     .Filter = "ID_Staff = 0"
  25.     .FilterOn = True
  26. End With
  27.  
  28.  
  29. End If
  30.  
May 2 '18 #5
Karen20785
10 New Member
I think I found a solution:

Expand|Select|Wrap|Line Numbers
  1. On Error GoTo Done
  2.  Dim db As DAO.Database
  3.     Dim rst As DAO.Recordset
  4.     Dim strSQL As String
  5.     Dim TheDate As Date
  6.      Dim lngStaff As Long
  7.  
  8.     Set db = CurrentDb
  9.  
  10.  
  11.     lngStaff = Me.ID_staff
  12.  
  13.  
  14.     strSQL = "SELECT max(Milestone_Date) as Dte " & _
  15.         "FROM qryvw_milestones " & _
  16.         "WHERE ((Milestone_Date<=now()) " & _
  17.         "AND (ID_staff = " & lngStaff & "))"
  18.     Set rst = db.OpenRecordset(strSQL)
  19.     TheDate = rst.Fields(0)
  20.     Me.Milestone_Date.SetFocus
  21.     DoCmd.FindRecord TheDate
  22.     Me.Milestone_Date.SetFocus
  23.  
  24.  
  25. Done:
  26. Exit Sub
  27.  
May 2 '18 #6
twinnyfo
3,653 Recognized Expert Moderator Specialist
I think you are trying to put the cart slightly before the horse here, but sometimes it's difficult to communicate properly via a forum.

First, you want to find out if the user has any milestones in your query. Depending on the results of that inquiry, then you use the Staff ID.

Here is a guess at what it might look like, but you will probably have to clean it up to suit your exact situation.

Expand|Select|Wrap|Line Numbers
  1. Private Sub Form_Load()
  2. On Error GoTo EH
  3.     Dim db          As DAO.Database
  4.     Dim rst         As DAO.Recordset
  5.     Dim strSQL      As String
  6.     Dim TheDate     As Date
  7.     Dim lngStaff    As Long
  8.     Dim fMilestone  As Boolean
  9.  
  10.     lngStaff = Me.ID_Staff
  11.     fMilestone = Nz(DLookup("ID_Staff", "qryvw_milestones", _
  12.         "ID_Staff = " & lngStaff), False)
  13.  
  14.     If fMilestone Then
  15.         strSQL = "SELECT max(Milestone_Date) as Dte " & _
  16.             "FROM qryvw_milestones " & _
  17.             "WHERE ((Milestone_Date<=now()) " & _
  18.             "AND (ID_staff = " & lngStaff & "))"
  19.         Set db = CurrentDb
  20.         Set rst = db.OpenRecordset(strSQL)
  21.         With rst
  22.             If Not .RecordCount = 0 Then
  23.                 TheDate = .Fields(0)
  24.                 Me.Milestone_Date.SetFocus
  25.                 DoCmd.FindRecord TheDate
  26.                 Me.Milestone_Date.SetFocus
  27.             End If
  28.             .Close
  29.         End With
  30.         db.Close
  31.         Set rst = Nothing
  32.         Set db = Nothing
  33.     Else
  34.         With Me!frmvw_milestones.Form
  35.             .Filter = "ID_Staff = 0"
  36.             .FilterOn = True
  37.         End With
  38.     End If
  39.  
  40.     Exit Sub
  41. EH:
  42.     MsgBox "There was an error loading the form!" & _
  43.         vbCrLf & vbCrLf & _
  44.         "Number: " & Err.Number & vbCrLf & _
  45.         "Desc.: " & Err.Description & vbCrLf & vbCrLf & _
  46.         "Please contact your Database Administrator.", _
  47.         vbCritical, "WARNING!"
  48.     Exit Sub
  49. End Sub
Notice lines 8-11. See how we have identified the employee, then we use that to look up that employee's milestones. If there are none assigned to that employee, the fMilestone flag is set to false. Then, we use that result to figure out what to do. If the mployee has milestones (and you can modify the DLookup criteria to match whatever you need to suit your purposes), then we go to that particular record. If not, then we filter the subform to show no records.

A couple additional thoughts (to help you out in the long-term, bigger scheme of things).

First, when posting your code, try, if at all possible, to post the entire procedure. Unless the procedure is huge and you are only having issues with a tiny portion of it. Yours is small enough that seeing the whole procedure is helpful. And always do a fresh copy and paste directly from your VBA editor.

Second, I have added "Error Handling" to your code (the On Error GoTo EH at the beginning of your code and EH at the end of your Code). This is a good habit to get into with all of your procedures (I am a notorious "harpy" about error handling on this forum, but I can't over emphasize the need for it). This keeps your code from "breaking" or simply dying in the middle of a user's session.

I've made some changes with how you manage your recordset. Notice lines 28 and 30-32. You should always close all your recordsets and DBs, and then set them to nothing. This frees up computer resources and can prevent other problems within your DB engine. Always another good habit to get into, not to mention that having extraneous declared objects open can cause the DB to sometimes get confused.

Finally, notice line 22. Even though you may KNOW that you will have at least one record in your recordset (and probably in your case only one record), it is also another good habit to check to see if there are any records before you start using the recordset's values. failing to do so can cause an error in those rare cases when there is no record.

Probably more than you wanted at this time, but these principles will help you along the way no mater how far you go with your Access/VBA projects.

Let me know how these changes worked out.
May 2 '18 #7
NeoPa
32,564 Recognized Expert Moderator MVP
Guys.

Be very careful of using Now() to compare with dates. Now() is a Date/Time value that includes the time element of now. Date() is another matter entirely and is nearly always what you need. Using Now() is one of those common errors used by developers until they realise that it really isn't what they mean at all.

Good luck :-)
May 3 '18 #8
Karen20785
10 New Member
Thanks Twinnyfo and NeoPa,

Sorry for the delay in responding back. I had back-to-back meetings all day. I definitely will try your suggestions tomorrow and let you how it works out. Karen
May 4 '18 #9
NeoPa
32,564 Recognized Expert Moderator MVP
No worries on that score Karen.

We fully understand that people work and have lives and all that stuff. We're the same too ;-)
May 4 '18 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

6
2648
by: Gerry Viator | last post by:
Hi all, I have a textbox were a time is typed in like: upto 4 numbers 1900 300 1000 1425 I would like as they type the text to show todays date plus the time they
2
38388
by: Chuck | last post by:
Using a macro to output a query to an Excel file. Is there a way to automatically add todays date in the file spec? As: C:\Access Data\ & todays date.xls Chuck ....
1
1919
by: Wes Brooks | last post by:
Hello expert, Please help me with the following problems. I have spent ages to resolve them but no luck. I have two forms. (1) "Document Reception Input Form" is the main form. The search field Document ID is unbound combo box. The table is Documents. (2) "Document Reception Subform" is the sub form in tabular form. The linked field...
20
14217
by: keri | last post by:
Hi, I am creating a table where I want to use the date as the primary key - and to automatically create a record for each working date (eg Mon to Fri) until 30 June 2007. Is this possible? I do not want my user to have to create a record for each date. Thanks,
2
3909
by: Drum2001 | last post by:
Hello, I am having isues with the following: I have two forms, a MAIN FORM with a SUB FORM: Within the MAIN FORM, I have an unbound textbox (Date Format) and a command button. Onload, the textbox defualts to Date(). The SUB FORM has a bound textbox (Date Format). I am trying to create the code for the command button to compare the
8
2416
by: Trev | last post by:
Hi Can anyone point me in the right direction here, I would like to open a table in access 2003 by date. I have an asp web page which needs to read data from a table with each days today's date (which ever day that is) then a new table is created with today's date. Example: I have a table called 17-may-2007 my ASP page reads this table...
3
4221
by: jonosborne | last post by:
Hi guys, im a bit of a novice being thrown in at the deep end ! Using MS Access 97 i have a table with data that is updated once a day from an Excel spreadsheet. I need a way of identifying when data was added to this table so i have added an extra field (titled 'Date') and need to create a query that updates the empty field with todays date, so...
7
6531
by: GraemeC | last post by:
I have a form (single record form) that loads records from a query that are sorted date order as the records are viewed in date order. Some dates are in the past and some are in the future. Currently the form opens on the last record and the date of that record can be 6 months out. The users would like the form to open on the record closest to the...
2
1183
Daniel B
by: Daniel B | last post by:
I have a form to create a new record, and when I open it I would like it to already have todays date displayed in the field. I am not quite sure how do that because I am not experienced in VB code. Any suggestions are much appreciated! Dan B.
0
1051
by: Alex Stewart | last post by:
Hi, I am a complete novice in VB. Here is what I need if anyone could help me I want to open a text file into excel and save it in a path as today’s date The problem I have is that the file name changes daily, so I have to search in the text document for a certain field, and as at today’s date.
0
7720
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7960
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7475
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7812
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6048
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5089
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3501
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3483
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1944
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.