首页 > 解决方案 > 使用条件从excel中的字符串中提取数字

问题描述

假设我们有这样的字符串并想从中输出数字。数字并不总是在开头,所以我想我也需要定义条件。

试过这个Excel:从日期字符串中提取数字 但不工作

在此处输入图像描述

我们如何从excel中的这种字符串中提取数字?

标签: excelexcel-formula

解决方案


恭喜,今天是您将一些知识添加到您的武器库的日子。如果您向其中添加 vba 公式,结果将如下所示:

在此处输入图像描述

要添加公式,请按Alt+F11并将以下代码粘贴到Modul1或 中Worksheet

Public Function ExtractString(myRange As Range) As String

    Dim i As Long
    Dim result As String
    Dim currentString As String
    Dim okIndex As Long

    okIndex = 1
    result = ""

    For i = 1 To Len(myRange.Text)
        currentString = Mid(myRange.Text, i, 1)
        If IsNumeric(currentString) And okIndex >= 1 Then
            result = result & currentString
            okIndex = okIndex + 1
        Else
            If okIndex > 1 Then okIndex = -1
        End If
    Next

    ExtractString = result

End Function

推荐阅读