如何提取数据

时间:2016-11-22 05:53:32

标签: excel excel-vba vba

我在Excel中遇到这个问题,我需要从一串文本中提取数据,如下所示。以下数据全部位于不同的行上。我试图仅将斜杠之间的数据提取为x/y/z/a/b/c格式,并忽略前面的其余数据。希望可以使用vba解决此问题。

一个例子:

s1 167.4/164.2/172.0/165.8/162.5/165.6 s2 163.6/164.1/167.2/167.1/165.6/167.6 S#1:0.1682/0.1646/0.1641/0.1653/0.1622/0.1642 S#2:0.1623/0.1621/0.1667/0.1680/0.1667/0.1643 s24=1903/1881/1873/1903/1915/1891 s25=1872/1858/1904/1879/1854/1868 SLOT 24:0.2031/0.1991/0.1959/0.1989/0.1987/0.2051 SLOT 25:0.2014/0.2019/0.2014/0.2033/0.2001/0.2017

2 个答案:

答案 0 :(得分:1)

正则表达式将是最有力的答案。

需要自定义VBA功能和表达式以满足您的要求。

详细指南:How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

您可以使用的正则表达式可能是:(?:\ s |:| =)。*

即。找到第一个空格或第一个:或第一个=,然后选择之后的所有内容。

答案 1 :(得分:0)

看看这个:

Public Sub RegExpExample()
    Dim rng As Range
    Dim c As Variant, arr As Variant
    Dim k As Long
    Dim regEx As Object
    Dim Match, Matches

    ' Uses late binding so no need to add references 
    Set regEx = CreateObject("VBScript.RegExp")

    ' Change this to match your range where your values are
    With Sheet2
        Set rng = .Range(.Cells(1, 1), .Cells(8, 1))
    End With
    ' Declare RegEx parameters
    With regEx
        .Pattern = "(?:\d*\.)?\d+"
        .IgnoreCase = True
        .Global = True
    End With
    ' Loop through each row
    For Each c In rng
        Set Matches = regEx.Execute(c)
        If Matches.Count > 0 Then
            ReDim arr(1 To Matches.Count)
            k = 1
            For Each Match In Matches
                arr(k) = Match
                k = k + 1
            Next Match
            ' Print back to worksheet
            Range(c.Offset(0, 1), c.Offset(0, UBound(arr))) = arr
        End If
    Next c

End Sub

您必须决定如何处理返回的第一列值,或等到RegEx更好的人提出答案