Excel Home
全球知名的Excel资源网站之一

VBA | 用自定义函数提取字符

先来看看一个表,也不知道哪个挨千刀的,在记录数据的时候搞成这个样子,都聚集在A1单元格。要将A1中的姓名和银行卡号分别提取出来,只需要一个自定义函数GetChar就可以轻松搞定。

C2单元格:=INDEX(GetChar($A$1,3),ROW(1:1))

D2单元格:=INDEX(GetChar($A$1,1),ROW(1:1))

银行卡号可以搞定,身份证号也很容易,还是这个挨千刀的记录员,把姓名和身份证号都登记在了A1单元格,有没有一种想动刀子的冲动?再次请出自定义函数GetChar:
C2单元格:=INDEX(GetChar($A$1,3),ROW(1:1))
D2单元格:=LEFT(INDEX(GetChar($A$1,1),ROW(1:1))&”X”,18)

那么这个神秘的GetChar到底是什么呢?

再和你赌5毛钱的,你现在的电脑里写完这个公式之后,你得到的结果是:#NAME?

它是来源于我独创的VBA自定义函数,在你的VBA模块中植入以下代码,来吧,和我一起轻松玩转提取字符:

Function GetChar(strChar As String, varType As Variant) ‘取值函数

    Dim objRegExp As Object
    Dim objMatch As Object
    Dim strPattern As String
    Dim arr
    Set objRegExp =CreateObject(“vbscript.regexp”)
    varType = LCase(varType)
    Select Case varType
        Case 1, “number”
            strPattern =”-?\d+(\.\d+)?”
        Case 2, “english”
            strPattern = “[a-z]+”
        Case 3, “chinese”
            strPattern =”[\u4e00-\u9fa5]+”

    End Select

    With objRegExp
        .Global = True
        .IgnoreCase = True
        .Pattern = strPattern
        Set objMatch = .Execute(strChar)
    End With

    If objMatch.Count = 0 Then
        GetChar = “”
        Exit Function
    End If

    ReDim arr(0 To objMatch.Count – 1)
    For Each cell In objMatch
        arr(i) = objMatch(i)
        i = i + 1
    Next
    GetChar = arr
    Set objRegExp = Nothing
    Set objMatch = Nothing
End Function

它的功能设计就是专门为提取字符的,语法为:GetChar(strChar,varType):

varType参数为1时,提取:数字

varType参数为2时,提取:英文

varType参数为3时,提取:汉字

赞(62)
未经允许不得转载:ExcelHome » VBA | 用自定义函数提取字符
分享到

关于我们联系我们
本站特聘法律顾问:李志群律师   沪ICP备11019229号-2

沪公网安备 31011702000001号

征信