excel - 从字母数字字符串中检索字母字符

标签 excel vba

怎么分手AB2468123

我尝试了以下方法:

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

我只想得到字母(字母)。

谢谢。

最佳答案

如何仅从输入字符串中检索字母:

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

编辑:为了完整性(和 Chris Neilsen)这里是 Regex方法:
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

关于excel - 从字母数字字符串中检索字母字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24691002/

相关文章:

excel - VBA用数组/字典加速For循环?

excel - 如何忽略 Excel VBA for App_SheetChange 中的某些事件?

c# - EPPlus - 导出带有前导单引号的字符串值

excel - Excel 中的错误?尽管单元格不为空,但显示空白区域

excel - Excel 中的 VBA : Runtime Error 1004

excel - 使用宏以编程方式删除我的工作簿中的所有代码

windows - 如何使用 VBA 执行 shell 命令?

vba - 在未打开的电子表格中使用 VBA FIND() 函数(或类比)

vba - 从多页表单中获取事件控件名称和值

excel - 我可以使用什么公式来插入 x 行,其中 x 是两个文本框响应之间的差异?