从字符串中提取带有小数的特定数字?

时间:2020-03-20 13:29:24

标签: excel vba

我想从字符串中提取数字,如下所示:

string =“ Vol。20.0 4.44 406.5 419.3 419.3”

我希望能够具体说明想要的数字,即GetNumber(string,2)= 4.44或GetNumber(string,4)= 419.3

使用vba函数或excel公式解决方案进行精细处理。

2 个答案:

答案 0 :(得分:0)

您还可以使用正则表达式

Public Function GetNumber(s As String, pos As Long) As String
' Add Microsoft VBScript Regular Expression 5.5 via Tools/References
    Dim regEx As RegExp
    On Error GoTo EH

    Set regEx = New RegExp

    With regEx
        .IgnoreCase = True
        .Global = True
        .Pattern = "-?\d*\.?\d+"

        If .Test(s) Then
            GetNumber = .Execute(s)(pos - 1)
        End If
    End With

    Exit Function

EH:
    GetNumber = ""

End Function


Sub TestIt()

Dim s As String

   s = "Vol. 20.0 4.44 406.5 419.3 419.3"    
   Debug.Print GetNumber(s, 2)

End Sub

答案 1 :(得分:0)

此代码删除了第一个数组变量,并允许用户选择要使用的元素。

<!-- https://mvnrepository.com/artifact/org.wildfly.bom/wildfly-jakartaee8-with-tools -->
<dependency>
    <groupId>org.wildfly.bom</groupId>
    <artifactId>wildfly-jakartaee8-with-tools</artifactId>
    <version>18.0.0.Final</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>