本文介绍了从字母数字字符串中检索字母字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何拆分 AB2468123
与
我尝试了以下这些行: p>
myStr =AB2468123
split(myStr,1OR2OR3.... ...9)
我只想得到字母(字母) >
谢谢。
解决方案
这样只能从输入字符串中检索字母:
函数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)
如果Asc(LCase(letter))> = 97 And Asc(LCase(letter))< = 122 then
letters = letters + letter
End If
Next
GetLettersOnly =字母
结束函数
Sub Test()
Debug.Print GetLettersOnly(abc123)//打印abc
Debug.Print GetLettersOnly(ABC123 )//打印ABC
Debug.Print GetLettersOnly(123)//打印没有
Debug.Print GetLettersOnly(abc123def)//打印abcdef
End Sub
编辑:为了完整性(和Chris Neilsen),这里是正则表达式
方式:
函数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
如果objRegEx.test(str)然后
设置match = objRegEx.Execute(str)
GetLettersOnly = match(0)
如果
结束函数
Sub test()
Debug.Print GetLettersOn ly(abc123)//打印abc
End Sub
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.
解决方案
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
这篇关于从字母数字字符串中检索字母字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!