定義一個自定義函數,把數字、英文、中文分別分離出來,要達到如下效果:
定義函數:
以上的思路是分析每一個字符,由函數參數分別進行判斷、提取。
重點要關注一下ASC()函數,在工作表中與VBA中都提供此函數:
返回與字符串的第一個字母對應的 ANSI 字符代碼。string 參數是任意有效的字符串表達式。如果 string 參數未包含字符,則將發生運行時錯誤。
Sub testasc()
For i = 2 To 21
Cells(i, 2) = VBA.Asc(Cells(i, 1))
Next i
End Sub
但以上提取數字的方式當數字有浮點數或負數時,會有些問題,浮點數和負數無法完整提出。如果使用正則表達式,整個字符串整體去匹配(不是單個字符匹配),可以解決這一問題:
自定義函數:
附代碼1:
Function sepTxt(rngStr As String, Optional n As Integer = False, Optional start_num As Integer = 1)
'【=sepTxt(A2,0)】:提取數字
'【=sepTxt(A2,1)】:提取中文
'【=sepTxt(A2,2)】:提取英文
Dim i As Integer
Dim s, MyString As String
Dim flag As Boolean
For i = start_num To Len(rngStr)
s = Mid(rngStr, i, 1) '相當於字符串顆粒化,操作字符串的每一個字符
If n = 1 Then '提取中文
flag = Asc(s) < 0 '如果是中文,flat為Ture
ElseIf n = 2 Then '提取英文
flag = s Like "[a-z,A-Z]"
ElseIf n = 0 Then '提取數字
flag = s Like "#"
End If
If flag Then MyString = MyString & s '字符串在舊值的基礎上更新,加上符合條件的字符
Next
sepTxt = IIf(n = 1 Or n = 2, MyString, Val(MyString))
End Function
附代碼2:
Function sep(strng, i As Integer, Optional ByVal fgf As String = "")
Dim regEx, Match, Matches
Set regEx = CreateObject("vbScript.regexp")
With regEx
If i = 0 Then .pattern = "([0-9].[0-9])|[0-9]|(-[0-9])"
If i = 1 Then .pattern = "[一-龥]"
If i = 2 Then .pattern = "[a-zA-Z]"
If i = 3 Then .pattern = "[^a-zA-Z0-9\\u4e00-\\u9fff\+]"
.IgnoreCase = True
.Global = True
Set Matches = .Execute(strng)
For Each Match In Matches
RetStr = RetStr & fgf & Match
Next
sep = Mid(RetStr, Len(fgf) + 1)
'sep = .Replace(strng, "") 'pattern要取非^
End With
End Function
-End-
閱讀更多 小智雅匯 的文章