Retrieve alpha characters from alphanumeric string

两盒软妹~` 提交于 2019-12-31 03:46:11

问题


How can I split up AB2468123 with excel-vba

I tried something along these lines:

myStr = "AB2468123"
split(myStr, "1" OR "2" OR "3"......."9")

I want to get only alphabet (letters) only.

Thanks.


回答1:


How about this to retrieve only letters from an input string:

Function GetLettersOnly(str As String) As String
    Dim i As Long, letters As String, letter As String

    letters = vbNullString

    For i = 1 To Len(str)
        letter = VBA.Mid$(str, i, 1)

        If Asc(LCase(letter)) >= 97 And Asc(LCase(letter)) <= 122 Then
            letters = letters + letter
        End If
    Next
    GetLettersOnly = letters
End Function

Sub Test()
    Debug.Print GetLettersOnly("abc123")      // prints "abc"
    Debug.Print GetLettersOnly("ABC123")      // prints "ABC"
    Debug.Print GetLettersOnly("123")         // prints nothing
    Debug.Print GetLettersOnly("abc123def")   // prints "abcdef"
End Sub

Edit: for completeness (and Chris Neilsen) here is the Regex way:

Function GetLettersOnly(str As String) As String
    Dim result As String, objRegEx As Object, match As Object

    Set objRegEx = CreateObject("vbscript.regexp")

    objRegEx.Pattern = "[a-zA-Z]+"
    objRegEx.Global = True
    objRegEx.IgnoreCase = True

    If objRegEx.test(str) Then
        Set match = objRegEx.Execute(str)
        GetLettersOnly = match(0)
    End If
End Function

Sub test()
    Debug.Print GetLettersOnly("abc123") //prints "abc"
End Sub



回答2:


This is what i have found out that works the best. It may be somewhat basic, but it does the job :)

    Function Split_String(Optional test As String = "ABC111111") As Variant
    For i = 1 To Len(test)
    letter = Mid(test, i, 1)
        If IsNumeric(letter) = True Then
           justletters = Left(test, i - 1)
           justnumbers = Right(test, Len(test) - (i - 1))
           Exit For
        End If
    Next
   'MsgBox (justnumbers)
   'MsgBox (justletters)

   'just comment away the answer you want to have :)
   'Split_String = justnumbers
   'Split_String = justletters

   End Function



回答3:


Simpler single shot RegExp

Sub TestIt()
MsgBox CleanStr("AB2468123")
End Sub

Function CleanStr(strIn As String) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
    .Pattern = "[^a-zA-Z]+"
    .Global = True
    CleanStr = .Replace(strIn, vbNullString)
End With
End Function



回答4:


Possibly the fastest way is to parse a Byte String:

Function alpha(txt As String) As String
  Dim b, bytes() As Byte: bytes = txt
  For Each b In bytes
    If Chr(b) Like "[A-Za-z]" Then alpha = alpha & Chr(b)
  Next b
End Function
  • More information here.


来源:https://stackoverflow.com/questions/24691002/retrieve-alpha-characters-from-alphanumeric-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!