一个自定义函数,轻松提取中文、数值和英文

先来看看一个表,也不知道哪个挨千刀的 , 在记录数据的时候搞成这个样子 , 都聚集在A1单元格 。

一个自定义函数,轻松提取中文、数值和英文

要将A1中的姓名和银行卡号分别提取出来,只需要一个自定义函数GetChar就可以轻松搞定 。
C2单元格:
=INDEX(GetChar($A$1,3),ROW(1:1))
D2单元格:
=INDEX(GetChar($A$1,1),ROW(1:1))
这个神秘的GetChar到底是什么呢?它是VBA自定义函数 。
右键单击工作表标签 , 插入,模块,然后将以下代码粘贴到模块里,好了 , 接下来就一起轻松玩转提取字符吧:
Function GetChar(strChar As String, varType As Variant) '取值函数Dim objRegExp As ObjectDim objMatch As ObjectDim strPattern As StringDim arrSet objRegExp = CreateObject("vbscript.regexp")varType = LCase(varType)Select Case varTypeCase 1, "number"strPattern = "-?d (.d )?"Case 2, "english"strPattern = "[a-z] "Case 3, "chinese"strPattern = "[u4e00-u9fa5] "End SelectWith objRegExp.Global = True.IgnoreCase = True.Pattern = strPatternSet objMatch = .Execute(strChar)End WithIf objMatch.Count = 0 ThenGetChar = ""Exit FunctionEnd IfReDim arr(0 To objMatch.Count - 1)For Each cell In objMatcharr(i) = objMatch(i)i = i1NextGetChar = arrSet objRegExp = NothingSet objMatch = NothingEnd Function
这个自定义函数的功能设计就是专门提取字符的,语法为:
GetChar(strChar,varType):
第二参数为1时提取数字
【一个自定义函数,轻松提取中文、数值和英文】第二参数为2时提取英文
第二参数为3时提取汉字


图文作者:翟振福

相关经验推荐