473,792 Members | 2,807 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generate Primary ID based on criteria

50 New Member
Hi,

I have a table name ExpenseClaim where it has a field named RefNo to store the Primary ID for each record.

In my form, I has a combo box named cboExpenseCode: -
1) If user select "Company Reimbursed", then the prefix for the Primary ID is P-xxx
2) If user select "Project Reimbursed", then the prefix for the Primary ID is OF-xxx

xxx- represent the incremental id (e.g OF-001 , OF-002 / P-001, P-002) for the different expense code selected.

My code goes here :

Expand|Select|Wrap|Line Numbers
  1. Private Sub cboExpenseCode_AfterUpdate()
  2.     If Me.NewRecord And Me.cboExpenseCode.Value = "Project Reimbursed" Then
  3.         Dim NextPRefNo As Long
  4.         NextPRefNo = Nz(DMax("Right ([RefNo],3)", "ProjectExpenses"), 0) + 1
  5.         Me![RefNo] = "P-" & Format(CStr(NextPRefNo), "000")
  6.     ElseIf Me.NewRecord And Me.cboExpenseCode.Value = "Company Reimbursed" Then
  7.         Dim NextOFRefNo As Long
  8.         NextOFRefNo = Nz(DMax("Right ([RefNo],3)", "ProjectExpenses"), 0) + 1
  9.         Me![RefNo] = "OF-" & Format(CStr(NextOFRefNo), "000")
  10.     End If
  11. End Sub
  12.  
But I get a problem here, the if let say the table has OF-001, the first ID value for Project Reimbursed will start with P-002. I want it to begin with P-001.
The DMax will only recognize the maximum value for the number. Can anyone please guide me how to get the output that I want? This should be easy, but I just cannot figure out the solution :(

Thank you very much.
Feb 18 '09 #1
9 3107
beemomo
50 New Member
I found the solution at last. I created two queries (MaxPRefNo & MaxOFRefNo) to store the Max value for the Primary ID starting with prefix -> OF- and P-.
Next, I edit to the DMax function as below:

For PRefNo:
Expand|Select|Wrap|Line Numbers
  1. NextPRefNo = Nz(DMax("Right ([MaxOfID],3)", "MaxPRefNo"), 0) + 1
  2.  
For OFRefNo:
Expand|Select|Wrap|Line Numbers
  1. NextOFRefNo = Nz(DMax("Right ([MaxOfID],3)", "MaxOFRefNo"), 0) + 1
  2.  
Feb 18 '09 #2
NeoPa
32,579 Recognized Expert Moderator MVP
This has never been an easy question (You're not the first to ask it).

There is a solution however, which involves using WHERE criteria in the DMax() function :
Expand|Select|Wrap|Line Numbers
  1. Private Sub cboExpenseCode_AfterUpdate()
  2.     Dim strExpenseCode As string, strWhere As String
  3.     Dim lngNextRef As Long
  4.  
  5.     If Me.NewRecord Then
  6.         strExpenseCode = ""
  7.         Select Case Me.cboExpenseCode
  8.         Case "Project Reimbursed"
  9.             strExpenseCode = "P-"
  10.         Case "Company Reimbursed"
  11.             strExpenseCode = "OF-"
  12.         Case '... Other possibilities easily added
  13.         End Select
  14.         If strExpenseCode > "" Then
  15.             strWhere = "[RefNo] Like '" & strExpenseCode & "*'"
  16.             lngNextRef = Val(Right(Nz(DMax("[RefNo]", _
  17.                                            "ProjectExpenses", _
  18.                                            strWhere), "000"), 3)) + 1
  19.             Me.RefNo = strExpenseCode & Format(lngNextRef, "000")
  20.         End If
  21.     End If
  22.     ...
  23. End Sub
Feb 18 '09 #3
NeoPa
32,579 Recognized Expert Moderator MVP
NB. This concept doesn't work well in a multi-user environment, as it's possible for another user to get exactly the same value if they select the expense code after someone else does, but before they have saved it away. You may need to consider this.

A solution is to determine the value only at the time of saving the new record. This seems strange but is actually more correct than showing a value which is currently not valid. Until the record has already been saved, the value shown is only a best guess - a logical estimate of what it's likely to end up being. It can only be known after the record's saved, so it should only be shown for an existing record.
Feb 18 '09 #4
ADezii
8,834 Recognized Expert Expert
@beemomo
It could actually be done with no Queries at all:
Expand|Select|Wrap|Line Numbers
  1. Dim strLastP As String
  2. Dim strLastOF As String
  3. Dim strNextP As String
  4. Dim strNextOF As String
  5.  
  6. strLastP = DLast("[RefNo]", "ProjectExpenses", "[RefNo] Like 'P*'")
  7. strLastOF = DLast("[RefNo]", "ProjectExpenses", "[RefNo] Like 'OF*'")
  8.  
  9. strNextP = Left$(strLastP, 2) & Format$(Val(Right$(strLastP, 3)) + 1, "000")
  10. strNextOF = Left$(strLastOF, 3) & Format$(Val(Right$(strLastOF, 3)) + 1, "000")
Feb 18 '09 #5
NeoPa
32,579 Recognized Expert Moderator MVP
While DLast() may work in a number of circumstances, it should not be relied upon to produce the highest number. At best it relies on the data being entered in a logical order. I would recommend using DMax().
Feb 18 '09 #6
ADezii
8,834 Recognized Expert Expert
@NeoPa
Wouldn't the Last Record be the highest ID Value (P-*/OF-*) assuming the logic is sound? If the data is not being entered in a logical order, the entries are essentially useless, correct?
Feb 18 '09 #7
NeoPa
32,579 Recognized Expert Moderator MVP
Not at all. That assumes things which are not supportable.

It assumes that :
  • All the data was entered via this form after it's working perfectly.
  • You know the order the records are stored in the table.
  • No records are added after any previous ones are deleted and the space re-used.
  • There is no point where the data is moved about by processes you neither know about nor control (EG. Export to another database; do some work; import it back in unspecified, or even different order).
Mainly though, it's just the wrong function. You're not after the Last assuming it's the Max - You're after the Max.

Sorry to sound critical ADezii. I'm simply answering the question as clearly as I can. I certainly don't see it as an ambiguous point. You can often get away with DLast() (for reasons you understand well), but it's not advisable for the reasons stated.
Feb 18 '09 #8
NeoPa
32,579 Recognized Expert Moderator MVP
I was also hoping to draw the OP's attention to the style of the code in my post.

It's clear from the code which scenario is covered at any point.
It doesn't repeat code unnecessarily.
It's flexible and easily extensible.

This is not to advertise how wonderful my code is, but hopefully to get the OP to try it out and see how few extra problems occur later due to the tidier code.
Feb 18 '09 #9
beemomo
50 New Member
Thanks to everyone for your clear explanations!
I am learning new things again. :)
Feb 19 '09 #10

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

Similar topics

3
2089
by: amywolfie | last post by:
Hi All: I would like to run a report based on criteria from 3 unbound combo boxes located on a parameter form (combo boxes are: cboCuisine, cboLocation, and cboRestaurant) The present code for the FIND button (using just cboCuisine for testing) is: Private Sub Command13_Click()
2
2926
by: neptune | last post by:
I have a query where each customer has an or . Sometimes both fields for a customer are populated, but if is null, then will be populated and vice versa. I have a form, , where I select a value for from a combo box. In my query I set the criteria for to ... My query finds the proper values for . Now I also want to find the values if I select a value for in a separate combo box. In both controls, OnChange, I set the value of
6
3817
by: Sebastien | last post by:
Hi, I am building a products database, linking sales and production. Each part has a unique sales Stock Code and Production Number. The sales stock code is a combination of letters and numbers taken from the part name (BrandA 300 4 Bladed : B3004B). The production number is a 4 or 5 digits number with first figure(s) indicating category (BrandA 300 4 Bladed: BrandA is category 1000. This Product would be 1003 if it was the third...
4
1860
by: misscrf | last post by:
Ok I have 2 issues. 1) I have a main candidate form with 2 subforms on a tab control: http://www.geocities.com/misscrf/images/contactcontinouscheckbox.jpg I have been encouraged to add these checkboxes, so that when there is more than one phone or address for a candidate, I can track which is the primary. My issue is that I have to control that only one address, for example, can be a primary for one candidate. Can anyone help me in...
12
1677
by: anna | last post by:
Map, generate, and maintain 50% of your .NET application code, namely your business and data objects. Use these objects in ASP.NET, Windows Forms, console or services applications. Business and Data Objects Framework -- Map objects to relational databases -- Embed SQL, stored procedure calls, and business rules -- Generate .NET components in C# and VB.NET -- Use components in your own high-traffic custom applications
1
2323
by: davidbennett | last post by:
Hello, I am new to MS Access. I have created a series of forms that users access to perform data entry. I now need to build in reporting functionality. I would like to create a form that has a drop down box where the user selects a value and then clicks a "generate report" button where data about the selected value is presented in a report. Can someone help get a beginner started on accomplishing this? Thanks,
6
2747
by: AA Arens | last post by:
Hi, I have a database with 2 main forms. Contacts and companies. I share the base with two others via LAN. On the companies form I have buttons to navigate throught the records (>400). We are mostly handling let say 5 companies. Every time I have to navigate or choose the find record button to get the right company. I am looking fo a feature to have listed in a combo list the last 5 visited records ("recently visited records").
0
1048
by: sonic | last post by:
I am working with a 3rd party control that does not follow the asp.net event model. I would like to make it post to current page, and fire a server side event. I would like to mimic the behavior of GridView Link column, with a non ..net grid control. the 3rd party grid supports a link column, but the only option there is to enter the link href address. This does not fit very well with asp.net model, and with my design, as i need to load...
11
4499
by: Alan Mailer | last post by:
A project I'm working on is going to use VB6 as a front end. The back end is going to be pre-existing MS Access 2002 database tables which already have records in them *but do not have any AutoNumber* fields in them. Correct me if I'm wrong, but I'm assuming this means that I cannot now alter these existing Access tables and change their primary key to an "AutoNumber" type. If I'm right about this, I need some suggestions as to the...
0
9670
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10430
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10159
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10000
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5436
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5560
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4111
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.