从不同字符长度的单元格中提取数字

我有一组单元格,string的第一个不会改变,它总是会(直到编码器改变它) 20字符(inc空格)。

然后我想从剩余的序列中提取3个数字(有些情况下是2个)。

 The monthly cost is 2 silver, 1 copper and 40 iron. The monthly cost is 1 silver, 94 copper and 40 iron. The monthly cost is 1 silver and 75 copper. The monthly cost is 8 silver and 40 copper. The monthly cost is 1 silver. The monthly cost is 99 silver, 99 copper and 99 iron. The monthly cost is 1 gold. 

在上面的示例中,可以看到前20个字符后没有设置值。

 1 or 99 silver 1 or 99 copper 0, 1 or 99 iron 

我不能得到一个序列,使所有的单元格正确,我已经尝试了以下内容:

 =IF(J7<>1,(MID(TRIM(J7),FIND(" iron",TRIM(J7))-2,FIND(" iron",TRIM(J7))-FIND(" iron",TRIM(J7))+3)),"") results in: #VALUE! (when no iron) =TRIM(MID(J6,FIND(" silver",J6)-2,LEN(J6)-FIND(" silver",J6)-26))&TRIM(MID(J6,FIND(" copper",J6)-2,LEN(J6)-FIND(" copper",J6)-16))&TRIM(MID(J6,FIND(" iron",J6)-2,LEN(J6)-FIND(" iron",J6)-3)) results in: 1 s9440 =MID(J7,31,2-ISERR(MID(J7,21,1)+0)) results in: nd 

如果我&单元格作为计算的一部分,那么他们就不会在下一个math步骤中进行计算,因为我必须在代码中允许spaces ,在可能有2位数字而不是单个数字的情况下。

 =MID(J5,SEARCH(" silver",J5,1)-2,2)&MID(J5,SEARCH(" copper",J5,1)-2,2)&MID(J5,SEARCH(" iron",J5,1)-2,2) results: 2 140 not: 2140 

我需要结束的是:

 2140 19440 175 840 1 999999 

提前谢谢了。

当涉及到string的模式匹配时,RegEx如果经常走的话。

在Excel中,这需要一个VBA解决scheme,使用“Microsoft VBScript Regular Expresions 5.5”的引用(如果您愿意,可以延迟访问)

作为UDF,这是您的案例的启动器

假设第一个原始数据在A1则将它用作=GetValues(A1)的公式。 根据需要复制尽可能多的行

这将从string中提取多达3个值。

 Function GetValues(r As Range) As Variant Dim re As RegExp Dim m As MatchCollection Dim v As Variant Dim i As Long Set re = New RegExp re.Pattern = "(\d+)\D+(\d+)\D+(\d+)" If re.test(r.Value) Then Set m = re.Execute(r.Value) Else re.Pattern = "(\d+)\D+(\d+)" If re.test(r.Value) Then Set m = re.Execute(r.Value) Else re.Pattern = "(\d+)" If re.test(r.Value) Then Set m = re.Execute(r.Value) End If End If End If If m Is Nothing Then GetValues = vbNullString Else For i = 0 To m.Item(0).SubMatches.Count - 1 v = v & m.Item(0).SubMatches(i) Next GetValues = v End If End Function 

这个公式适用于我的数据,假设在单元格A1中的文本string

=IFERROR(MID(A1,SEARCH("silver",A1)-3,2)+0,"")&IFERROR(MID(A1,SEARCH("copper",A1)-3,2)+0,"")&IFERROR(MID(A1,SEARCH("iron",A1)-3,2)+0,"")

我假定你不想要“黄金”的价值?

既然你只是删除数字,你可以使用一个简单的RegExp如果你想要的VBA路线:

 Function GetDigits(strIn As String) As String Dim objRegex As Object Set objRegex = CreateObject("vbscript.regexp") With objRegex .Pattern = "[^\d]+" .Global = True GetDigits = .Replace(strIn, vbNullString) End With End Function 

这是另一种使用工作表公式的方法,用于返回string中的所有数字。 哈兰格罗夫很多年前就把它放在那里。

首先定义一个名称(带有工作簿范围):

Seq指:= ROW(INDEX($ 1:$ 65536,1,1):INDEX($ 1:$ 65536,255,1))

然后,假设您的string在A1中,请使用以下数组input的公式。 (公式是通过在按Enter的同时按住ctrl + shift来 input的 (如果你这样做的话,Excel会在公式周围放置大括号{...}

 =SUM(IF(ISNUMBER(1/(MID(A1,Seq,1)+1)),MID(A1,Seq,1)*10^MMULT(-(Seq<TRANSPOSE(Seq)),-ISNUMBER(1/(MID(A1,Seq,1)+1)))))