从字符串中删除字符

时间:2012-02-07 13:56:55

标签: excel vba

我有以下功能,但我希望它能做相反的事情,例如返回坏的字符而不是我指定的字符

此功能允许您指定两个字符串。要解析的字符串以及要从指定的第一个字符串保留的字符串 - 返回已编辑的字符串

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

由于 罗布

4 个答案:

答案 0 :(得分:2)

只需添加= 0

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

当找不到匹配项时,InStr函数返回0。

答案 1 :(得分:1)

您可以使用分割功能,如下例所示。

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

答案 2 :(得分:0)

也刚刚写了这篇文章 - 以为我会分享一下

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

答案 3 :(得分:0)

换句话说,你想从源字符串中删除(删除)字符?如果是这样,这是一个答案:

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