+ Reply to Thread
Results 1 to 8 of 8

Extract and return only alpha, numeric and also specified characters from a parameter str

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    03-05-2007
    Location
    Falmouth, VA now, Palm Bay, FL for 2 yrs, was Colorado Springs, CO for ten years; Cedark Park, TX; Zeeland, MI; Wilmette, IL; Princeton Junction, NJ; NY, NY
    MS-Off Ver
    365
    Posts
    615

    Extract and return only alpha, numeric and also specified characters from a parameter str

    Happy New Year Everyone!

    I am monkeying around with some code written by Peter Albert.

    I wish to extend the ability to not only extract specified categories (alpha, numeric, and alpha-numeric)(This is presently accomplished by passing the optional parameter "strLimit"), but also to be able to be fed additional special characters in any given call.

    The first part was easy by simply implementing an additional parameter and If/End structure such as:

    Function AlphaNumericOnly(strSource As String, Optional strLimit As String) As String
    'Based on original code by Peter Albert at http://stackoverflow.com/questions/15723672/how-to-remove-all-non-alphanumeric-characters-from-a-string-except-period-and-sp
    ' If Optional strLimit is missing or is "an" then returns both alpha and numeric
    ' If Optional strLimit is an "a" then returns strictly alpha
    ' If Optional strLimit is an "n" then returns strictly numeric
    ' If Optional strLimit is an "d" then returns numeric and a slash for dates
        Dim i As Integer
        Dim strResult As String
        
        If bPubSkip Then 'To allow for not processing when called for the last time by a CHANGE event after an EXIT event:
            AlphaNumericOnly = strSource
        Else
            If strLimit = "an" Or IsMissing(strLimit) Or strLimit = "" Then    ' Alpha and Numeric
                For i = 1 To Len(strSource)
                    Select Case Asc(Mid(strSource, i, 1))
                        Case 48 To 57, 65 To 90, 97 To 122:
                            strResult = strResult & Mid(strSource, i, 1)
                    End Select
                Next
            ElseIf strLimit = "a" Then    ' Alpha
                For i = 1 To Len(strSource)
                    Select Case Asc(Mid(strSource, i, 1))
                        Case 65 To 90, 97 To 122:
                            strResult = strResult & Mid(strSource, i, 1)
                    End Select
                Next
            ElseIf strLimit = "n" Then    'Numeric
                For i = 1 To Len(strSource)
                    Select Case Asc(Mid(strSource, i, 1))
                        Case 48 To 57, 44, 46:
                            strResult = strResult & Mid(strSource, i, 1)
                    End Select
                Next
            ElseIf strLimit = "N" Then    'Numeric & hyphen ONLY
                For i = 1 To Len(strSource)
                    Select Case Asc(Mid(strSource, i, 1))
                        Case 48 To 57:
                            strResult = strResult & Mid(strSource, i, 1)
                    End Select
                Next
                AlphaNumericOnly = strResult
            ElseIf strLimit = "d" Then    'Numeric & slash ONLY
                For i = 1 To Len(strSource)
                    Select Case Asc(Mid(strSource, i, 1))
                        Case 47 To 57:
                            strResult = strResult & Mid(strSource, i, 1)
                    End Select
                Next
            End If
            AlphaNumericOnly = strResult
        End If
    End Function
    In an effort to convert it to the feed of specific characters, my first step was to try to feed a string variable to the Case, first based upon the major category I wanted to extract (strLimit). Since Case takes literal parameters, I attempted to use Evaluate, but that failed with a "Type Mismatch" error:

    
    Function TestOnly(strSource As String, Optional strLimit As String, Optional strExceptions As String) As String
    ' If Optional strLimit is missing or is "an" then returns both alpha and numeric
    ' If Optional strLimit is an "a" then returns strictly alpha
    ' If Optional strLimit is an "n" then returns strictly numeric
        Dim i As Integer
        Dim strCase As String
        Dim strResult As String
        
        If strLimit = "an" Then
            strCase = "48 To 57, 65 To 90, 97 To 122:"
        ElseIf strLimit = "a" Then
            strCase = "65 To 90, 97 To 122:"
        ElseIf strLimit + "n" Then
            strCase = "48 To 57, 44, 46:"
        End If
        
        
        For i = 1 To Len(strSource)
            Select Case Asc(Mid(strSource, i, 1))
                Case [strCase]
                    strResult = strResult & Mid(strSource, i, 1)
            End Select
        Next
        TestOnly = strResult
    
    End Function
    The train of thought was that if I can feed a string that I can build upon to CASE, then I could concatenate in to strCase the additional ASCII codes which I would build off of a third parameter sent to this function, which would be parsed into codes (strExceptions).

    Is there a way that my attack can be accomplished, or need I work on another direction? I do have an ugly solution that calls for an If/End control and provides for a different literal string for every combination of Major Categories plus other characters I might wish to include (the start of which you see in the first example above), but as the variations grew I wanted to make the code adapt instead of adding another "ElseIf" each time I wanted to address yet another character combination!

    I regret that my ability to conceive of variations to experiment with are limited by my understanding when faced with the Select Case structure taking literal parameters and not variables. I have researched the internet for a bit but could not yet find a solution.

    Thank-you for considering my problem!

  2. #2
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Extract and return only alpha, numeric and also specified characters from a parameter

    Hi Bruce,

    You may want to try using the 'like' command. For more information see https://msdn.microsoft.com/en-us/lib.../gg251796.aspx

    Regular expressions are more powerful than the 'like' command, but can become complicated to use very quickly. For a good tutorial see http://analystcave.com/excel-regex-tutorial/

    The following example code using 'like' may help you out:
    Option Explicit
    
    Sub TestNumbers()
    
      Const strSource = "abc123456def7890xyz"
      
      Dim i As Long
      Dim c As String
      Dim strResult As String
    
      For i = 1 To Len(strSource)
        c = Mid(strSource, i, 1)
        If c Like "#" Then
          strResult = strResult & Mid(strSource, i, 1)
        End If
      Next i
      
      Debug.Print "Testing for Numbers only"
      Debug.Print "Source String: " & strSource
      Debug.Print "Result String: " & strResult
    
    End Sub
    
    Sub TestAlphaUpperCase()
    
      Const strSource = "abc1234/\ABC56def7890xyz"
      
      Dim i As Long
      Dim c As String
      Dim strResult As String
    
      For i = 1 To Len(strSource)
        c = Mid(strSource, i, 1)
        If c Like "[A-Z]" Then
          strResult = strResult & Mid(strSource, i, 1)
        End If
      Next i
      
      Debug.Print "Testing for Alpha Upper Case only"
      Debug.Print "Source String: " & strSource
      Debug.Print "Result String: " & strResult
    
    End Sub
    
    Sub TestAlphaLowerCase()
    
      Const strSource = "abc1234/\ABC56def7890xyz"
      
      Dim i As Long
      Dim c As String
      Dim strResult As String
    
      For i = 1 To Len(strSource)
        c = Mid(strSource, i, 1)
        If c Like "[a-z]" Then
          strResult = strResult & Mid(strSource, i, 1)
        End If
      Next i
      
      Debug.Print "Testing for Alpha Lower Case only"
      Debug.Print "Source String: " & strSource
      Debug.Print "Result String: " & strResult
    
    End Sub
    
    Sub TestAlpha()
    
      Const strSource = "abc1234/\ABC56def7890xyz"
      
      Dim i As Long
      Dim c As String
      Dim strResult As String
    
      For i = 1 To Len(strSource)
        c = Mid(strSource, i, 1)
        If c Like "[A-Za-z]" Then
          strResult = strResult & Mid(strSource, i, 1)
        End If
      Next i
      
      Debug.Print "Testing for Alpha only"
      Debug.Print "Source String: " & strSource
      Debug.Print "Result String: " & strResult
    
    End Sub
    
    Sub TestAlphaAndNumbers()
    
      Const strSource = "abc1234/\ABC56def7890xyz"
      
      Dim i As Long
      Dim c As String
      Dim strResult As String
    
      For i = 1 To Len(strSource)
        c = Mid(strSource, i, 1)
        If c Like "[A-Za-z0-9]" Then
          strResult = strResult & Mid(strSource, i, 1)
        End If
      Next i
      
      Debug.Print "Testing for Alpha and Numbers only"
      Debug.Print "Source String: " & strSource
      Debug.Print "Result String: " & strResult
    
    End Sub
    
    Sub TestNumbersAndHyphens()
    
      Const strSource = "AAA03-12-1996BBBxyz"
      
      Dim i As Long
      Dim c As String
      Dim strResult As String
    
      For i = 1 To Len(strSource)
        c = Mid(strSource, i, 1)
        If c Like "[0-9-]" Then
          strResult = strResult & Mid(strSource, i, 1)
        End If
      Next i
      
      Debug.Print "Testing for Numbers and Hyphens only"
      Debug.Print "Source String: " & strSource
      Debug.Print "Result String: " & strResult
    
    End Sub
    
    Sub TestNumbersAndSlashes()
    
      Const strSource = "AAA03/12/1996BBBxyz"
      
      Dim i As Long
      Dim c As String
      Dim strResult As String
    
      For i = 1 To Len(strSource)
        c = Mid(strSource, i, 1)
        If c Like "[0-9/]" Then
          strResult = strResult & Mid(strSource, i, 1)
        End If
      Next i
      
      Debug.Print "Testing for Numbers and Slashes only"
      Debug.Print "Source String: " & strSource
      Debug.Print "Result String: " & strResult
    
    End Sub
    
    Sub TestAnythingButLowerCase()
    
      Const strSource = "AAA03/12/1996BBBxyz"
      
      Dim i As Long
      Dim c As String
      Dim strResult As String
    
      For i = 1 To Len(strSource)
        c = Mid(strSource, i, 1)
        If c Like "[!a-z]" Then
          strResult = strResult & Mid(strSource, i, 1)
        End If
      Next i
      
      Debug.Print "Testing for Anything But Lower Case"
      Debug.Print "Source String: " & strSource
      Debug.Print "Result String: " & strResult
    
    End Sub
    Lewis
    Last edited by LJMetzger; 01-20-2017 at 10:50 AM.

  3. #3
    Forum Contributor
    Join Date
    03-05-2007
    Location
    Falmouth, VA now, Palm Bay, FL for 2 yrs, was Colorado Springs, CO for ten years; Cedark Park, TX; Zeeland, MI; Wilmette, IL; Princeton Junction, NJ; NY, NY
    MS-Off Ver
    365
    Posts
    615

    Re: Extract and return only alpha, numeric and also specified characters from a parameter

    In that I am always revising what I write I suppose there are some modifications that can be made to the following to make it more efficient, but I wanted to post this in the event anyone else might be looking for a similar solution-

    Many thanks to Peter Albert and LJMetzger!

    Function ExtractOnly(strSource As String, Optional strLimit As String, Optional strExceptions As String) As String
    ' Inspired by original code by Peter Albert at http://stackoverflow.com/questions/15723672/how-to-remove-all-non-alphanumeric-characters-from-a-string-except-period-and-sp and
    ' changes suggested by LJMetzger at http://www.excelforum.com/showthread.php?t=1170465&p=4564494#post4564494
    
    ' strSource is the string you are feeding the function
    ' strExceptions is a string of additional characters which you wish to include
    
    ' If Optional strLimit is missing or is "an" then returns both alpha and numeric
    ' If Optional strLimit is an "a" then returns strictly alpha
    ' If Optional strLimit is an "n" then returns strictly numeric
    
        Dim i As Long
        Dim strCase As String
        Dim strResult As String
        Dim c As String
        
        If strLimit = "" Then strLimit = "an"
    
        If strLimit = "an" Then
            strCase = "A-Za-z0-9"
        ElseIf strLimit = "a" Then
            strCase = "A-Za-z"
        ElseIf strLimit = "n" Then
            strCase = "0-9"
        End If
        
        If Len(strExceptions) > 0 Then
            For i = 1 To Len(strExceptions)
                strCase = strCase & Mid(strExceptions, i, 1)
            Next i
        End If
    
      For i = 1 To Len(strSource)
        c = Mid(strSource, i, 1)
        If c Like "[" & strCase & "]" Then
          strResult = strResult & Mid(strSource, i, 1)
        End If
      Next i
    
        ExtractOnly = strResult
    
    End Function
    Last edited by brucemc777; 01-20-2017 at 05:44 PM. Reason: Forgot to add the assignment if strLimit was empty.

  4. #4
    Forum Contributor
    Join Date
    03-05-2007
    Location
    Falmouth, VA now, Palm Bay, FL for 2 yrs, was Colorado Springs, CO for ten years; Cedark Park, TX; Zeeland, MI; Wilmette, IL; Princeton Junction, NJ; NY, NY
    MS-Off Ver
    365
    Posts
    615

    Re: Extract and return only alpha, numeric and also specified characters from a parameter

    Interesting! From my initial testing I find that the Like statement can be fed a string variable in the form of

    Like "[" & strTest & "]"

    So in the structure you presented above, if all works well, I should be able to achieve what I wish.

    Thank-you very much!

  5. #5
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Extract and return only alpha, numeric and also specified characters from a parameter

    Hi Bruce,

    Thanks for the kind words and the rep points. Since you are doing the calculations in a loop and the VBA Interpreter (Compiler) does not optimize, the following change will make the routine more efficient. The time savings will not be noticeable unless you call this routine often using large data strings:

      strCase  = "[" & strCase & "]"
    
      For i = 1 To Len(strSource)
        c = Mid(strSource, i, 1)
        If c Like strCase  Then
          strResult = strResult & Mid(strSource, i, 1)
        End If
      Next i
    Lewis

  6. #6
    Forum Contributor
    Join Date
    03-05-2007
    Location
    Falmouth, VA now, Palm Bay, FL for 2 yrs, was Colorado Springs, CO for ten years; Cedark Park, TX; Zeeland, MI; Wilmette, IL; Princeton Junction, NJ; NY, NY
    MS-Off Ver
    365
    Posts
    615

    Re: Extract and return only alpha, numeric and also specified characters from a parameter

    I see; so the program does not have to re-evaluate the concatenation over and over. Thanks!

    Also I was wondering about something from the start - you used

    Const strSource = "abc123456def7890xyz"

    I would have written something like:
    Dim strSource as String
    strSource = "abc123456def7890xyz"

    Can you explain the difference?

  7. #7
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Extract and return only alpha, numeric and also specified characters from a parameter

    In this case they are equivalent, and it took less keystrokes.

    A constant (Const) is a variable whose value can not be changed. Down at the bits and bytes level (which I used to care about in the old days when where an item was stored really mattered), they are also probably stored by VBA in different places.

    The discussion about 'Global Variables' near the end of the following link may help with the the following discussion: http://www.functionx.com/vbaexcel/Lesson03.htm

    Example code:
    Option Explicit
    
    Public Const sControlSheetNAME = "Sheet1"
    
    Private Const xSecondsPerDAY As Double = 86400#
    
    Private Const xPi = 3.1416
    
    Sub abc()
    
      Const xPi As Double = 3.14
    
      '... other code
      
      MsgBox xPi
      
    End Sub
    
    Sub def()
    
      MsgBox xPi
      
    End Sub
    When I need a variable whose value will not change, I declare it as a constant. My personal convention is to CAPITALIZE the last few characters in a constant name, so I know it is a constant just by looking at the variable name. A compiler error will occur if you try to assign a value to a constant. Regular variables (and constants) have 3 basic types of scope (availability):

    a. Global scope accessible by all code in any module in the Workbook. The keyword Public is used, and the constant is declared before the first routine and after 'Option Explicit' (if 'Option Explicit' is used - highly recommended).

    b. Global scope accessible by all code in any routine in the same module. The keyword Private is used, and the constant is declared before the first routine and after 'Option Explicit'.

    c. Local scope accessible only by code in the same routine.

    It is very important to note that the same 'Constant Name' can be declared in more than one place and can have different values such as xPi above. Lower level variable (and constant) declarations ('Local Scope') take precedence over 'Module Scope' (Private), and 'File Scope' (Public).

    'Module Scope' (Private) takes precedence over 'File Scope' (Public). When I have 'Public' variables (and constants) in a project, I usually put them all in their own code Module which I call ModConstantsAndGlobals.

    I hope this helps.

    Lewis

  8. #8
    Forum Contributor
    Join Date
    03-05-2007
    Location
    Falmouth, VA now, Palm Bay, FL for 2 yrs, was Colorado Springs, CO for ten years; Cedark Park, TX; Zeeland, MI; Wilmette, IL; Princeton Junction, NJ; NY, NY
    MS-Off Ver
    365
    Posts
    615

    Re: Extract and return only alpha, numeric and also specified characters from a parameter

    Thank-You!!!

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 2
    Last Post: 03-17-2016, 08:55 AM
  2. Separating Alpha and Numeric Characters
    By genoa in forum Excel Formulas & Functions
    Replies: 3
    Last Post: 08-22-2015, 04:57 AM
  3. Separating alpha, numeric and other characters
    By ldg in forum Excel General
    Replies: 10
    Last Post: 08-04-2015, 02:16 PM
  4. Separate Alpha and numeric characters
    By sivdin in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 08-09-2013, 02:50 AM
  5. Replies: 2
    Last Post: 06-18-2010, 05:10 PM
  6. [SOLVED] only extract numeric value from alpha numeric cell
    By Fam via OfficeKB.com in forum Excel General
    Replies: 5
    Last Post: 04-26-2006, 01:55 PM
  7. [SOLVED] Can you ID a cell that has both Alpha AND Numeric characters?
    By Phil in forum Excel Formulas & Functions
    Replies: 5
    Last Post: 04-18-2006, 04:35 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1