从Excel中的单元格中提取多个数据

时间:2018-03-16 08:02:48

标签: regex excel excel-vba excel-formula vba

screenshot我需要从单个单元格中提取三个变量。我已经能够使用正则表达式提取前4个数字。现在我还想提取接下来的四位数字(1970)我需要添加什么来获得它?

截图:

Function getZip(addr As String)

Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.Pattern = "(\d{4})"
RE.Global = True
RE.IgnoreCase = True

Set allMatches = RE.Execute(addr)

If (allMatches.Count <> 0) Then
    result = allMatches.Item(0).submatches.Item(0)
End If

getZip = result

End Function

1 个答案:

答案 0 :(得分:1)

我只想添加3个模式和一个参数PatternNo来选择使用哪种模式:

Function getZip(addr As String, PatternNo As Long)       
    Dim allMatches As Object
    Dim RE As Object
    Set RE = CreateObject("vbscript.regexp")

    Dim Patterns As Variant 'define 3 patterns 0 to 2
    Patterns = Array("([0-9]{4}) .*", "[0-9]{4} (.*)", "bygget i ([0-9]{4})")

    'you might want to add an error handling here (see end of this answer)

    RE.Pattern = Patterns(PatternNo) 'choose pattern by its number
    RE.Global = True
    RE.IgnoreCase = True

    Set allMatches = RE.Execute(addr)
    If (allMatches.Count <> 0) Then
        result = allMatches.Item(0).submatches.Item(0)
    End If

    getZip = result   
End Function

我建议这些模式:

最好检查PatternNo是否不超过数组Patterns中的模式数,如果出现错误则返回错误:

If PatternNo < 0 Or PatternNo > UBound(Patterns) Then
    getZip = 'return your desired error here
    Exit Function
End If

如果根本找不到匹配项,您可能还想要返回错误。

相关问题