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
Bookmarks