Home » excel » excel – Remove chars from a string

excel – Remove chars from a string

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have the following function but I want it to do the opposite eg return the bad chars not the ones I specify

This function lets you specify a two strings. The string you want to parse and a string of chars that you would like to keep from the first string specified – The edited string is returned

Function GETALPHANUMERIC(text, str_all)

 For lenstr = 1 To Len(text)
     If InStr(str_all, LCase(Mid(text, lenstr, 1))) Then
         GETALPHANUMERIC = GETALPHANUMERIC & Mid(text, lenstr, 1)
     End If
 Next

 End Function

Thanks
Rob

How to&Answers:

Just add = 0 :

If InStr(str_all, LCase(Mid(text, lenstr, 1))) = 0 Then

The InStr function returns 0 when no match is found.

Answer:

You could use the split function like in the example below.

Sub test()

  Dim s As String
  Dim result As String

  s = "abcXdefXghiX"
  result = excludeCharacter(s, "X")

  MsgBox s & " excluding X is " & result

End Sub

Function excludeCharacter(originalString As String, exclude As String) As String

  Dim sArray() As String
  Dim result As String
  Dim i As Long

  sArray = Split(originalString, exclude)

  For i = 0 To UBound(sArray, 1)
    result = result & sArray(i)
  Next i

  excludeCharacter = result

End Function

Answer:

Also just wrote this too – thought I would share just incase

Function BadChar(text, str_all)

     For lenstr = 1 To Len(text)
     If InStr(str_all, LCase(Mid(text, lenstr, 1))) = 0 Then
         BadChar = BadChar & Mid(text, lenstr, 1)
     End If
Next

End Function

Answer:

In other words, you want to strip out (remove) characters from the source string? If so, here’s an answer for that:

Function StripChars(source As String, chars As String)
    Dim pos As Long
    For i = 1 To Len(chars)
        Do
            pos = InStr(1, source, Mid(chars, i, 1), VbCompareMethod.vbTextCompare)
            If pos > 0 Then
                source = Mid(source, 1, pos - 1) & Mid(source, pos + 1)
            Else
                Exit Do
            End If
        Loop
    Next i
    StripChars = source
End Function