2010-08-23 61 views

回答

8

像這樣的東西應該爲你做的伎倆:

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

您可以簡化功能。你並不需要'currentCharacter';你的測試可能是'If IsNumeric(Mid(s,i,1))然後......' – e100 2010-08-23 13:29:23

+0

@ e100 - 非常真實。打破它使它更具可讀性,這就是我在回答這個複雜程度的問題時的工作原理,因爲我工作的基礎是OP可能需要更簡單/更清晰的代碼來幫助理解=) – Rob 2010-08-23 13:33:18

0

如果速度是一個問題,這將運行略高於剝奪快(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 
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 

然後你只用​​調用它。

+0

+1我看到我們有類似的想法,你快一點! – 2010-08-23 14:07:42

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 
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 
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 
相關問題