Skip to content

Stripping Characters from a String

Here’s another way to strip a character from a text string, a simpler alternative to the StripCharacter function.

Q: Robert Greiff writes to say that there is a simpler way to strip a character from a text string than the StripCharacter function I described in WAW 4.24. He proposes using the Replace function instead, as in this line of code:

Replace(“##HE#L###L0##”, “#”, “”)

 

gives “HELLO”






 

A: He is absolutely correct about this – For the earlier example, I cut down another function, which removes all non-alphanumeric characters from a string (you do need more complex code for that), but for removing a single character Replace is better. For removing any and all non-alphanumeric characters from a text string, here is the original StripNonAlphanumericChars function:

Public Function StripNonAlphaNumericChars(strText As String) As String

‘Strips a variety of non-alphanumeric characters from a text string

‘Created by Helen Feddema 10-15-97

‘Modified by Ruud H.G. van Tol 6-18-99

‘Last modified by Helen Feddema 7-2-99

 

On Error GoTo ErrorHandler

 

Dim strTestString As String

Dim strTestChar As String

Dim lngFound As Long

Dim i As Integer

Dim strStripChars As String

 

strStripChars = ” `~!@#$%^&*()-_=+[{]};:’,<.>/?” & Chr$(34) _

   & Chr$(13) & Chr$(10)

strTestString = strText

i = 1

Do While i <= Len(strTestString)

   ‘Find a strippable character

   strTestChar = Mid$(strTestString, i, 1)

   lngFound = InStr(strStripChars, strTestChar)

   If lngFound > 0 Then

      strTestString = left(strTestString, i – 1) & Mid(strTestString, i + 1)

   Else

      i = i + 1

   End If

Loop

 

StripNonAlphaNumericChars = strTestString

 

ErrorHandlerExit:

   Exit Function

ErrorHandler:

   MsgBox “Error No: ” & Err.Number & “; Description: ” & _

      Err.Description Resume ErrorHandlerExit

 

End Function

About this author

Office 2024 - all you need to know. Facts & prices for the new Microsoft Office. Do you need it?

Microsoft Office upcoming support end date checklist.