VBA。如何在字符串中查找第一个数字的位置

时间:2010-08-23 13:00:28

标签: vba digit

我有字符串“ololo123”。 我需要获得第一位数的位置 - 1。 如何设置搜索掩码?

6 个答案:

答案 0 :(得分:9)

这样的事情可以帮到你:

Public Function GetPositionOfFirstNumericCharacter(ByVal s As String) As Integer
    For i = 1 To Len(s)
        Dim currentCharacter As String
        currentCharacter = Mid(s, i, 1)
        If IsNumeric(currentCharacter) = True Then
            GetPositionOfFirstNumericCharacter = i
            Exit Function
        End If
    Next i
End Function

然后你可以这样称呼它:

Dim iPosition as Integer
iPosition = GetPositionOfFirstNumericCharacter("ololo123")

答案 1 :(得分:7)

这是一种轻量级且快速的方法,可以避免正则表达式/引用添加,从而有助于提高开销和可传输性。

Public Function GetNumLoc(xValue As String) As Integer

For GetNumLoc = 1 To Len(xValue)
    If Mid(xValue, GetNumLoc, 1) Like "#" Then Exit Function
Next

GetNumLoc = 0

End Function

答案 2 :(得分:2)

您的环境不确定,但这在Excel 2010中有效

'Added reference for Microsoft VBScript Regular Expressions 5.5

Const myString As String = "ololo123"
Dim regex As New RegExp
Dim regmatch As MatchCollection

regex.Pattern = "\d"
Set regmatch = regex.Execute(myString)
MsgBox (regmatch.Item(0).FirstIndex)   ' Outputs 5

答案 3 :(得分:2)

我实际上有这个功能:

Public Function GetNumericPosition(ByVal s As String) As Integer
    Dim result As Integer
    Dim i As Integer
    Dim ii As Integer

    result = -1
    ii = Len(s)
    For i = 1 To ii
        If IsNumeric(Mid$(s, i, 1)) Then
            result = i
            Exit For
        End If
    Next
    GetNumericPosition = result
End Function

答案 4 :(得分:1)

你可以试试正则表达式,然后你就会遇到两个问题。我的VBAfu不符合要求,但我会试一试:

Function FirstDigit(strData As String) As Integer
    Dim RE As Object REMatches As Object

    Set RE = CreateObject("vbscript.regexp")
    With RE
        .Pattern = "[0-9]"
    End With

    Set REMatches = RE.Execute(strData)
    FirstDigit = REMatches(0).FirstIndex
End Function

然后您只需使用FirstDigit("ololo123")调用它。

答案 5 :(得分:0)

如果速度是一个问题,这将比Robs(noi Rob)运行得快一点:

Public Sub Example()
    Const myString As String = "ololo123"
    Dim position As Long
    position = GetFirstNumeric(myString)
    If position > 0 Then
        MsgBox "Found numeric at postion " & position & "."
    Else
        MsgBox "Numeric not found."
    End If
End Sub

Public Function GetFirstNumeric(ByVal value As String) As Long
    Dim i As Long
    Dim bytValue() As Byte
    Dim lngRtnVal As Long
    bytValue = value
    For i = 0 To UBound(bytValue) Step 2
        Select Case bytValue(i)
            Case vbKey0 To vbKey9
                If bytValue(i + 1) = 0 Then
                    lngRtnVal = (i \ 2) + 1
                    Exit For
                End If
        End Select
    Next
    GetFirstNumeric = lngRtnVal
End Function