VBA|在单元格中分离英文、数字、中文的自定义函数(使用正则)

定义一个自定义函数,把数字、英文、中文分别分离出来,要达到如下效果:

VBA|在单元格中分离英文、数字、中文的自定义函数(使用正则)

定义函数:

VBA|在单元格中分离英文、数字、中文的自定义函数(使用正则)

以上的思路是分析每一个字符,由函数参数分别进行判断、提取。

重点要关注一下ASC()函数,在工作表中与VBA中都提供此函数:

返回与字符串的第一个字母对应的 ANSI 字符代码。string 参数是任意有效的字符串表达式。如果 string 参数未包含字符,则将发生运行时错误。

Sub testasc()

For i = 2 To 21

Cells(i, 2) = VBA.Asc(Cells(i, 1))

Next i

End Sub

VBA|在单元格中分离英文、数字、中文的自定义函数(使用正则)

但以上提取数字的方式当数字有浮点数或负数时,会有些问题,浮点数和负数无法完整提出。如果使用正则表达式,整个字符串整体去匹配(不是单个字符匹配),可以解决这一问题:

VBA|在单元格中分离英文、数字、中文的自定义函数(使用正则)

自定义函数:

VBA|在单元格中分离英文、数字、中文的自定义函数(使用正则)

附代码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-


分享到:


相關文章: