如何提取数字 UNTIL a space is reached in a string using Excel 2010?

How to extract numbers UNTIL a space is reached in a string using Excel 2010?

我需要从以下字符串中提取代码:72381 Test 4Dx for Worms。代码是 72381,我正在使用的函数非常出色地从字符串中提取所有数字并返回 723814,它从代码描述中提取 4。实际代码只有 72381。这些代码的长度各不相同,并且在描述开始之前总是跟在 space 之后;然而,描述中也有 space。这是我在之前搜索中找到的正在使用的函数:

Function OnlyNums(sWord As String)          
    Dim sChar As String         
    Dim x As Integer            
    Dim sTemp As String         

    sTemp = ""          
    For x = 1 To Len(sWord)         
        sChar = Mid(sWord, x, 1)            
        If Asc(sChar) >= 48 And _           
          Asc(sChar) <= 57 Then         
            sTemp = sTemp & sChar           
        End If          
    Next            
    OnlyNums = Val(sTemp)           
End Function        

您正在寻找查找功能。示例:

或 VBA instr() and left()

因为您知道模式始终是代码后跟 space,只需使用字符串的 left 作为使用 instr 找到的第一个 space 的字符数.上面立即 window 中的样本。循环会很慢,虽然它可以验证它们是数字,但如果你知道模式是代码那么为什么还要麻烦 space?

在 C# 代码中的类似情况下,我在找到 space 字符 (32) 的第一个实例后提前离开循环。在 VBA 中,您将使用 Exit For。

如果字符串描述部分的第一个字符从来不是数字,您可以使用 VBA Val(string) 函数 return 第一个非数字字符之前的所有数字字符-数字字符。

Function GetNum(sWord As String)
    GetNum = Val(sWord)
End Function

请参阅 Val(string) 函数的 syntax 了解其用法的完整详细信息。

你可以完全摆脱这个功能并使用这个:

split("72381 Test 4Dx for Worms"," ")(0)

这会将字符串拆分为一个数组,使用“ ”作为拆分字符。然后它向我们展示了数组中的地址 0(第一个元素)

在您的函数的上下文中,如果您对使用它一无所知,那就是:

Function OnlyNums(sWord As String)
    OnlyNums = Split(sWord, " ")(0)
End Function

虽然我喜欢 Mark 解决方案的简单性,但您可以使用下面的高效解析器来改进逐字符搜索(以处理不以数字开头的字符串)。

测试

Sub test()
MsgBox StrOut("72381 Test 4Dx")
End Sub

代码

Function StrOut(strIn As String)
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
    .Pattern = "^(\d+)(\s.+)$"
    If .test(strIn) Then
        StrOut = .Replace(strIn, "")
    Else
        StrOut = "no match"
    End If
End With
End Function