Results 1 to 7 of 7
  1. #1
    IncidentalProgrammer is offline Competent Performer
    Windows XP Access 2007
    Join Date
    Aug 2014
    Location
    Texas
    Posts
    156

    Taking and editing first two words from text string to create unique ID.


    Hi, all!

    I cannot, for the life of me, get this to work. What I'm trying to do (and this wasn't my idea; my boss wants it this way) is to take the client name the user enters on the client creation form, and create their unique ID with it. These names can be as few as two words, or sometimes around five (they're businesses).

    The words I need to make the ID are just the first two. They might be under four letters, but if they are more than four letters long each, I have to cut them down to four. I then need to concatenate them, convert to all caps, and add "-##" to the end. The "##" is a two digit number to help distinguish those with similar names. (For example, we might have "First State Bank of ThisState" and "First State Bank of ThatState", so they would both be "FIRSSTAT", so the first one entered needs to get -01, and the second -02. I asked my boss about doing first and last word, and she wants first two.)

    I've tried the Allen Brown ParseWord method, and my variables are coming up blank when I debug.print. Has anyone had to do something like this before? She won't budge on the format, and she wants it done by the system (rather than the users), but I'm just not having any luck.

  2. #2
    June7's Avatar
    June7 is offline VIP
    Windows 7 64bit Access 2010 32bit
    Join Date
    May 2011
    Location
    The Great Land
    Posts
    52,930
    I found Allen's code but really need to analyze your adaptation. Post your code or database. Follow instructions at bottom of my post.

    What if words are less than 4 letters? What if first word is The or A, etc?

    Does this unique identifier serve any real purpose in the grand scheme of the business operations - like stock IDs for NYSE?
    How to attach file: http://www.accessforums.net/showthread.php?t=70301 To provide db: copy, remove confidential data, run compact & repair, zip w/Windows Compression.

  3. #3
    IncidentalProgrammer is offline Competent Performer
    Windows XP Access 2007
    Join Date
    Aug 2014
    Location
    Texas
    Posts
    156
    I'm worried I also may not be understanding how I'm supposed to interact with the AB code. I didn't change anything in his, so it's:
    Code:
    Function ParseWord(varPhrase As Variant, ByVal iWordNum As Integer, Optional strDelimiter As String = " ", _
        Optional bRemoveLeadingDelimiters As Boolean, Optional bIgnoreDoubleDelimiters As Boolean) As Variant
    On Error GoTo Err_Handler
        'Purpose:   Return the iWordNum-th word from a phrase.
        'Return:    The word, or Null if not found.
        'Arguments: varPhrase = the phrase to search.
        '           iWordNum = 1 for first word, 2 for second, ...
        '               Negative values for words form the right: -1 = last word; -2 = second last word, ...
        '               (Entire phrase returned if iWordNum is zero.)
        '           strDelimiter = the separator between words. Defaults to a space.
        '           bRemoveLeadingDelimiters: If True, leading delimiters are stripped.
        '               Otherwise the first word is returned as null.
        '           bIgnoreDoubleDelimiters: If true, double-spaces are treated as one space.
        '               Otherwise the word between spaces is returned as null.
        'Author:    Allen Browne. http://allenbrowne.com. June 2006.
        Dim varArray As Variant     'The phrase is parsed into a variant array.
        Dim strPhrase As String     'varPhrase converted to a string.
        Dim strResult As String     'The result to be returned.
        Dim lngLen As Long          'Length of the string.
        Dim lngLenDelimiter As Long 'Length of the delimiter.
        Dim bCancel As Boolean      'Flag to cancel this operation.
        '*************************************
        'Validate the arguments
        '*************************************
        'Cancel if the phrase (a variant) is error, null, or a zero-length string.
        If IsError(varPhrase) Then
            bCancel = True
        Else
            strPhrase = Nz(varPhrase, vbNullString)
            If strPhrase = vbNullString Then
                bCancel = True
            End If
        End If
        'If word number is zero, return the whole thing and quit processing.
        If iWordNum = 0 And Not bCancel Then
            strResult = strPhrase
            bCancel = True
        End If
        'Delimiter cannot be zero-length.
        If Not bCancel Then
            lngLenDelimiter = Len(strDelimiter)
            If lngLenDelimiter = 0& Then
                bCancel = True
            End If
        End If
        '*************************************
        'Process the string
        '*************************************
        If Not bCancel Then
            strPhrase = varPhrase
            'Remove leading delimiters?
            If bRemoveLeadingDelimiters Then
                strPhrase = Nz(varPhrase, vbNullString)
                Do While Left$(strPhrase, lngLenDelimiter) = strDelimiter
                    strPhrase = Mid(strPhrase, lngLenDelimiter + 1&)
                Loop
            End If
            'Ignore doubled-up delimiters?
            If bIgnoreDoubleDelimiters Then
                Do
                    lngLen = Len(strPhrase)
                    strPhrase = Replace(strPhrase, strDelimiter & strDelimiter, strDelimiter)
                Loop Until Len(strPhrase) = lngLen
            End If
            'Cancel if there's no phrase left to work with
            If Len(strPhrase) = 0& Then
                bCancel = True
            End If
        End If
        '*************************************
        'Parse the word from the string.
        '*************************************
        If Not bCancel Then
            varArray = Split(strPhrase, strDelimiter)
            If UBound(varArray) >= 0 Then
                If iWordNum > 0 Then        'Positive: count words from the left.
                    iWordNum = iWordNum - 1         'Adjust for zero-based array.
                    If iWordNum <= UBound(varArray) Then
                        strResult = varArray(iWordNum)
                    End If
                Else                        'Negative: count words from the right.
                    iWordNum = UBound(varArray) + iWordNum + 1
                    If iWordNum >= 0 Then
                        strResult = varArray(iWordNum)
                    End If
                End If
            End If
        End If
        '*************************************
        'Return the result, or a null if it is a zero-length string.
        '*************************************
        If strResult <> vbNullString Then
            ParseWord = strResult
        Else
            ParseWord = Null
        End If
    Exit_Handler:
        Exit Function
    Err_Handler:
        'Call LogError(Err.Number, Err.Description, "ParseWord()")
        Resume Exit_Handler
    End Function
    And then I tried programming a button. I'd initially thought the AB code was meant to be a Standard Module, but was getting errors until I moved it in with the rest of the code on the form. This code has a couple of different methods I tried; this is just what it is as of right now:
    Code:
    Private Sub btnID_Click()
         'Generate Client ID based on name user enters.
         'Declare variables.
        Dim strName As String   'Client Name user entered.
        Dim strOne As String    'First word in client name field.
        Dim strTwo As String    'Second word in client name field.
        Dim strFHalf As String  'First half of ID.
        Dim strSHalf As String  'Secoond half of ID.
        Dim strID As String     'Client ID (minus numbers)
         'Store user-entered client name in variable.
    '    strName = Me.ctlEntPrimName.Value
    '    Debug.Print
        
         'Parse first word from client name, convert to upper case.
        strOne = ParseWord([ctlEntPrimName], 1, , True, True)
        Debug.Print
         'Parse second word from client name, covnert to upper case.
        strTwo = ParseWord([ctlEntPrimName], 1, , True, True)
        Debug.Print
         'If first word longer than 4 letters, trim to 4.
        If Len(strOne) > 4 Then
            strFHalf = Left$(strOne, 4)
            Else: strFHalf = strOne
        End If
        Debug.Print
         'If second word longer than 4 letters, trim to 4.
        If Len(strTwo) > 4 Then
            strSHalf = Left$(strTwo, 4)
            Else: strSHalf = strTwo
        End If
        Debug.Print
         'Combine the two halves.
        strID = strFHalf & strSHalf
        Debug.Print
        
    'Me.ctlEntID = Left([ctlEntPrimName], InStr(InStr(1, [ctlEntPrimName]) + 1, [ctlEntPrimName]) - 1)
    'Debug.Print
    End Sub
    Our clients are lending institutions, and I've never seen one start with "A". "The" is fine, for my purposes; in my code, I tried to accomodate that by only trimming to four letters if the words were longer than 4.

    These IDs are very important. They're the Primary Key for the table, and identify the client and everything (accounts, policies, contacts, etc) linked to the client.

  4. #4
    June7's Avatar
    June7 is offline VIP
    Windows 7 64bit Access 2010 32bit
    Join Date
    May 2011
    Location
    The Great Land
    Posts
    52,930
    What do you want to do if words are less then 4 characters - accept the shorter ID, such as THEFIRS?

    The two calls for parsing function reference the same value for the iWordNum argument - I expect should be 1 and 2 respectively.

    Learn to debug code. Stepping through code is common technique. Refer to link at bottom of my post for debugging guidelines.

    Allen's function is generic code designed to handle error issues and be called from anywhere. Following is simple, specialized code that assumes there are always at least two words in name.

    Code:
    Private Sub btnID_Click()
    Dim ary As Variant, strID As String
    If IsNull(Me.ctlEntPrimName) Then
        MsgBox "Enter company name."
        Me.ctlEntPrimName.SetFocus
    Else
        ary = Split(Me.ctlEntPrimName, " ")
        strID = Left(ary(1), 4) & Left(ary(2), 4)
        If IsNull(Me.ID) Then
            Me.ID = strID & "0" & DCount("ID", "tablename", "ID LIKE '" & strID & "*'") + 1
        End If
    End If
    End Sub
    All this still relies on user to click the button to generate ID before leaving the record. What if they forget? Need more code to deal with that. In my db, the ID is generated and record committed when user clicks button to input a new record - then form opens to this new record for input of more data. And I have more code that allows them to abort the record - the existing new ID is used for next record login (my ID's are not dependent on data in the record). The more 'user friendly', the more code.

    What do you want to do if company reorganizes and changes name? How will existing records be connected to the new company ID? Is this even a concern?

    IDs that are dependent on data are usually a bad schema.
    How to attach file: http://www.accessforums.net/showthread.php?t=70301 To provide db: copy, remove confidential data, run compact & repair, zip w/Windows Compression.

  5. #5
    IncidentalProgrammer is offline Competent Performer
    Windows XP Access 2007
    Join Date
    Aug 2014
    Location
    Texas
    Posts
    156
    Thanks so much, June7! And thank for your patience. I'm trying to learn to debug, but I haven't gotten very good at it yet; I don't think it helps that I'm learning all of this horrifically backwards (heck, I just got a crash course in scripting, this morning). I always learn a lot from your posts, though. I made some minor modifications to the code, that are creating the format my boss was looking for. I hadn't really worked with arrays yet (read about them, yes, but used them, no), so this was a great learning opportunity for me.

    Code:
    Private Sub btnID_Click()'Generate Client ID.
    Dim ary As Variant
    Dim FHalf As String
    Dim SHalf As String
    If IsNull(Me.ctlEntPrimName) Then
        MsgBox "Enter company name."
        Me.ctlEntPrimName.SetFocus
    Else
        ary = Split(Me.ctlEntPrimName, " ")
        FHalf = UCase(Left$(ary(0), 4))
        SHalf = UCase(Left$(ary(1), 4))
        If IsNull(Me.ctlEntID) Then
            Me.ctlEntID = FHalf & SHalf & "-0" & DCount("EntID", "tblEntity", "EntID LIKE '" & FHalf & SHalf & "*'") + 1
        End If
    End If
    And yeah, I had asked about the "The"s and such, and those are just to be used as-is, even if it results in a shorter name. She has a very particular naming convention she likes.

    Thanks so much for your help!

  6. #6
    June7's Avatar
    June7 is offline VIP
    Windows 7 64bit Access 2010 32bit
    Join Date
    May 2011
    Location
    The Great Land
    Posts
    52,930
    Glad you have a solution. Sorry I forgot arrays are zero-based by default.

    A minor change suggested. I should have put the If IsNull(Me.ctrlEntID) condition before populating array and string variables. No need to do those if the record already has an ID.
    How to attach file: http://www.accessforums.net/showthread.php?t=70301 To provide db: copy, remove confidential data, run compact & repair, zip w/Windows Compression.

  7. #7
    IncidentalProgrammer is offline Competent Performer
    Windows XP Access 2007
    Join Date
    Aug 2014
    Location
    Texas
    Posts
    156
    Oh, I thought you did that as a teaching thing. It certainly taught me that they do!

    That's a very good point. I just moved it. I'm going to go back over other code I've got to check for the same thing, because I'm sure I've done it, myself!

Please reply to this thread with any new information or opinions.

Similar Threads

  1. Swap words from a string.
    By tigorin in forum Access
    Replies: 13
    Last Post: 04-07-2014, 02:37 PM
  2. Replies: 3
    Last Post: 01-01-2014, 11:21 PM
  3. Replies: 3
    Last Post: 07-26-2012, 03:09 PM
  4. Replies: 4
    Last Post: 12-02-2011, 11:20 AM
  5. Replies: 1
    Last Post: 05-30-2011, 09:38 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Other Forums: Microsoft Office Forums