• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 580
  • Last Modified:

Excel VBA - take out leading and trailing non-alpha characters in a given txt string

I have a cell (actually single-field merged range) with a text string.  I need to take out the initial and trailing end characters that are NOT alpha.  

So if the string is
;&3abc@wer!;er3ruu.rst.!     the result will be     3abc@wer!;er3ru.rst
only the initial and trailing non-alpha chars were removed.  The embedded non-alpha chars remain.

The solution could be something like two loops, one for the initial chars, the other for the end chars:

while initial char is not alpha
  remove initial char
next

while last char is not alpha
  remove last char
next

Thanks, --Andres
0
AndresHernando
Asked:
AndresHernando
2 Solutions
 
Patrick MatthewsCommented:
Add this function to a regular VBA module:

Function RegExpReplace(LookIn As String, PatternStr As String, Optional ReplaceWith As String = "", _
    Optional ReplaceAll As Boolean = True, Optional MatchCase As Boolean = True, _
    Optional MultiLine As Boolean = False)
    
    ' Function written by Patrick G. Matthews.  You may use and distribute this code freely,
    ' as long as you properly credit and attribute authorship and the URL of where you
    ' found the code
    
    ' For more info, please see:
    ' http://www.experts-exchange.com/articles/Programming/Languages/Visual_Basic/Using-Regular-Expressions-in-Visual-Basic-for-Applications-and-Visual-Basic-6.html
    
    ' This function relies on the VBScript version of Regular Expressions, and thus some of
    ' the functionality available in Perl and/or .Net may not be available.  The full extent
    ' of what functionality will be available on any given computer is based on which version
    ' of the VBScript runtime is installed on that computer
    
    ' This function uses Regular Expressions to parse a string, and replace parts of the string
    ' matching the specified pattern with another string.  The optional argument ReplaceAll
    ' controls whether all instances of the matched string are replaced (True) or just the first
    ' instance (False)
    
    ' If you need to replace the Nth match, or a range of matches, then use RegExpReplaceRange
    ' instead
    
    ' By default, RegExp is case-sensitive in pattern-matching.  To keep this, omit MatchCase or
    ' set it to True
    
    ' If you use this function from Excel, you may substitute range references for all the arguments
    
    ' Normally as an object variable I would set the RegX variable to Nothing; however, in cases
    ' where a large number of calls to this function are made, making RegX a static variable that
    ' preserves its state in between calls significantly improves performance
    
    Static RegX As Object
    
    If RegX Is Nothing Then Set RegX = CreateObject("VBScript.RegExp")
    With RegX
        .Pattern = PatternStr
        .Global = ReplaceAll
        .IgnoreCase = Not MatchCase
        .MultiLine = MultiLine
    End With
    
    RegExpReplace = RegX.Replace(LookIn, ReplaceWith)
    
End Function

Open in new window


Then, use it in a formula like this:

=RegExpReplace(A2,"^[^A-Za-z0-9]+|[^A-Za-z0-9]+$")

For more about Regular Expressions, please see:

http://www.experts-exchange.com/Programming/Languages/Visual_Basic/A_1336-Using-Regular-Expressions-in-Visual-Basic-for-Applications-and-Visual-Basic-6.html
0
 
etech0Commented:
Use the clean function
=clean(a1)
0
 
Patrick MatthewsCommented:
The CLEAN() function removes non-printing characters (e.g., tab, line feed, carriage return), not non-alphanumeric characters.
0
 
Glenn RayExcel VBA DeveloperCommented:
This code follows your original idea of having two loops process the leading three and trailing three characters.   It acts only on the active cell (i.e., where cursor is placed)

The current example only displays the result in a message box; the final line (22) that is commented out would overwrite the existing value.  Just remove the apostrophe (and comment out the preceding line)

Sub Clean_Leading_Trailing()
    Dim c, x As Integer
    Dim strCurrent, strCleaned As String
    strCurrent = ActiveCell.Value
    strCleaned = Mid(strCurrent, 4, Len(strCurrent) - 6)
    
    For x = 3 To 1 Step -1
        c = Asc(Mid(strCurrent, x, 1))
        Select Case c
            Case 48 To 57, 65 To 90, 97 To 122
                strCleaned = Mid(strCurrent, x, 1) & strCleaned
        End Select
    Next x
    For x = 2 To 0 Step -1
        c = Asc(Mid(strCurrent, Len(strCurrent) - x, 1))
        Select Case c
            Case 48 To 57, 65 To 90, 97 To 122
                strCleaned = strCleaned & Mid(strCurrent, Len(strCurrent) - x, 1)
        End Select
    Next x
    MsgBox "Original: " & strCurrent & vbLf & "Revised: " & strCleaned
    'ActiveCell.value = strCleaned
End Sub

Open in new window

0
 
AndresHernandoAuthor Commented:
Glenn, nicely done.  A couple tweaks and I'm making it work for all cases (not just initial/trailing three characters).  Thanks!  I'm awarding you 400pts

Matthew, your solution adds value.  Not quite for my current problem, but it will come in handy down the road.  Thanks.  Remaining 100pts to you.

etech0, thanks for your input too.

--Andres
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now