14

文字列「ololo123」があります。最初の桁の位置を取得する必要があります-1.検索のマスクを設定するには?

4

6 に答える 6

11

これは、正規表現/参照の追加を回避する軽量で高速な方法です。これにより、オーバーヘッドと可搬性が向上し、利点が得られます。

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
于 2015-08-06T19:09:10.863 に答える
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")
于 2010-08-23T13:10:02.230 に答える
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
于 2010-08-23T14:19:46.087 に答える
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
于 2010-08-23T14:01:29.577 に答える
1

正規表現を試すことができますが、2 つの問題が発生します。私の 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")

于 2010-08-23T13:27:59.197 に答える
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
于 2010-08-23T13:14:36.747 に答える