问题
I have the text "abcd 24 ef-gh" in an excel cell.
I need to get rid of "24" and "-" but keep all letters and spaces.
I have a function that loops through the text and identifies letters using the like operator. For some reason, it doesn't exclude the "24" nor the "-" for which I added a replace statement before the loop:
Function StripNonAlpha(TextToReplace As String) As String
Dim i As Integer
Dim a, b, c As String
a = Replace(TextToReplace, "-", " ")
For i = 1 To Len(a)
b = Mid(a, i, 1)
If b Like "[A-Z,a-z, ]" Then
c = c & b
End If
Next i
StripNonAlpha = c
End Function
I would have liked to use regex instead of this loop, but I didn't figure out the regex to use with VBA when I found a lot of examples for other languages.
Any regex suggestion is welcome, but I would also like to know why my loop is not behaving as expected.
回答1:
Use a simple regexp like this to keep your desired characters (ie remove anything that is not a-z, A-Z or a space)
Update:edit made to replace - with " " prior to regexp stripping
Function StripNonAlpha(TextToReplace As String) As String
Dim ObjRegex As Object
Set ObjRegex = CreateObject("vbscript.regexp")
With ObjRegex
.Global = True
.Pattern = "[^a-zA-Z\s]+"
StripNonAlpha = .Replace(Replace(TextToReplace, "-", Chr(32)), vbNullString)
End With
End Function
回答2:
You will need to add a reference to the Regex Library see this
Try this pattern
regEx.Pattern = "(\w\w\w\w)\s\d\d\s(\w\w)\D(\w\w)"
This will give you three groupings abcd ef gh that you can then work with. Hope this helps!
来源:https://stackoverflow.com/questions/20736071/vba-exclude-special-characters-and-numbers-but-keep-spaces-from-string