从单个字段中提取多个数据

时间:2013-11-23 11:40:52

标签: excel vba excel-vba

我目前正在尝试找到一个解决方案来处理包含一些信息的单个excel字段。我将向您展示可能包含这些字段的示例:

Field A1 : Coral Helm 7.154€ 21-22.12.13 

Field A2 : Wall of Spear 5€8-15.10.11

Field A3 : Clockwork Avian TBD 12-15.12.12

Field A4 : FellwarStone4-14-8.12.13

Field A5 : YotianSoldierTBD15-8-13

所以为了解释一下,基本上这是卡的价格,日期范围如21-22.12.13意味着从21.12.13到22.12.13。 正如你所看到的,有时单词之间没有空格,所以我不能简单地使用LEFT(),MID(),RIGHT()函数。

我在网上搜索是否仅通过使用excel公式来检查是否可行,但似乎使用VBA来处理这类问题会更​​好。 如果有人知道如何处理它可能会很好。

1 个答案:

答案 0 :(得分:0)

尝试通过RegExp对象使用Regular Expressions,您可以通过进入VBA IDE,单击工具--->将其包含到VBA项目中。引用...并选中“Microsoft VBScript Regular Expressions 5.5”旁边的框

以下模式可以匹配并拆分您列出的每个项目,“FellwarStone4-14-8.12.13”除外:

"^([\w\s]+?(?=\s*TBD|\s*[0-9.]+€))\s*(TBD|[0-9.]+€)(.+)$"

以下是如何使用RegExp对象的示例:

Public Sub SplitCell(cellvalue As String)
    Dim oRegExp As New RegExp
    Dim oMatches As MatchCollection
    Dim oMatch As Match
    Dim submatches() As String
    With oRegExp
        .Pattern = "^([\w\s]+?(?=\s*TBD|\s*[0-9.]+€))\s*(TBD|[0-9.]+€)\s*(.+)$"
        .Global = True
        .IgnoreCase = False
        .Multiline = False
        Set oMatches = .Execute(cellvalue)
    End With
    If oMatches.Count <> 0 Then
        MsgBox "Description: """ & oMatches.Item(0).submatches.Item(0) & """"
        MsgBox "Price: """ & oMatches.Item(0).submatches.Item(1) & """"
        MsgBox "Date: """ & oMatches.Item(0).submatches.Item(2) & """"
    Else
        MsgBox "Could not split cell value! It did not match the pattern."
    End If
End Sub