用自定义函数可以解决:
在Excel中按Alt+F11,打开VBA编辑器。单击菜单“插入→模块”,在代码窗口中输入下列代码:
Function GetNums(rCell As Range, num As Integer) As String
Dim Arr1() As String, Arr2() As String
Dim chr As String, Str As String
Dim i As Integer, j As Integer
On Error GoTo line1
Str = rCell.Text
For i = 1 To Len(Str)
chr = Mid(Str, i, 1)
If (Asc(chr) < 48 Or Asc(chr) > 57) Then
Str = Replace(Str, chr, " ")
End If
Next
Arr1 = Split(Trim(Str))
ReDim Arr2(UBound(Arr1))
For i = 0 To UBound(Arr1)
If Arr1(i) <> "" Then
Arr2(j) = Arr1(i)
j = j + 1
End If
Next
GetNums = IIf(num <= j, Arr2(num - 1), "")
line1:
End Function
该自定义函数定义了两个参数,第一个参数指定字符串所在的单元格,第二个参数指定提取字符串中的第几个数值。如果字符串中仅包含2个数值,而第二个参数大于2,则函数会返回空。
返回Excel工作表界面。假如上述字符串在A2单元格中,在B2中输入:
=Getnums(A2,1)
公式将以文本形式返回字符串中的第一个数值。要得到字符串中的第N个数值,将公式中的第二个参数“1”替换为N即可:
=Getnums(A2,3)