2016-01-21 69 views
7

我在一個單元格中有一個字符串,可以說它說「客戶端參考:F123456PassPlus」。 字符串在數字前可能沒有字母,可能數字中有符號,字母和數字之間可能有空格。 我需要僅提取數字作爲變量。我有代碼來完成它,但它不知道何時停止循環遍歷字符串。它應該在數字或符號以外的東西停止,但它會繼續。Excel VBA通​​過一串數字循環,直到找到一個字母

IsNumber = 1 
ref = "" 
If branch = "" Then 
    e = b 
Else 
    e = b + 1 
End If 
f = 1 
While IsNumber = 1 
    For intpos = 1 To 15 
     ref = Mid(x, e, f) 
     f = f + 1 
     Select Case Asc(ref) 
      Case 45 To 57 
       IsNumber = 1 
      Case Else 
       IsNumber = 0 
       Exit For 
     End Select 
    Next 
    IsNumber = 0 
Wend 
任何變量的信件有沒有定義先前已經被定義

,E告訴代碼從哪裏開始複製,x是包含字符串的單元格。現在,它一切正常,它從數字開始並複製它們並將它們構建成一個更大更大的字符串,但它只會在intpos達到15時停止。

+0

無論你想結束子任何地方,只要添加'退出子'。 – BruceWayne

+0

我需要宏來知道它何時得到了一個字母(或者最好在之前),然後我會在代碼中使用'Exit For'。用我寫的東西,我認爲它應該這樣做,但顯然不是。 –

+1

您是否debug.print Asc(ref)查看值? – CPMunich

回答

3

我擺脫ASC的檢查和添加對你建立的數值「字符串」之前傳遞每個字符檢查。

IsNumber = 1 
ref = "" 
If branch = "" Then 
    e = b 
Else 
    e = b + 1 
End If 
f = 1 
While IsNumber = 1 
    For intpos = 1 To 15 
     char = Mid(x, e + intpos, 1) 
     f = f + 1 
     If IsNumeric(char) Then 
      ref = Mid(x, e, f) 
      IsNumber = 1 
     Else 
      IsNumber = 0 
      Exit For 
     End If 
    Next 
    IsNumber = 0 
Wend 
2

此代碼鬆散地基於您的作品產生「12345」)。對於大字符串或更復雜的提取需求,我會考慮學習正則表達式COM對象。

Function ExtractNumber(ByVal text As String) As String 

    ExtractNumber = "" 

    foundnumber = False 

    For e = 1 To Len(text) 
    ref = Mid(text, e, 1) 
     Select Case Asc(ref) 
      Case 45 To 57 'this includes - . and /, if you want only digits, should be 48 to 57 
       foundnumber = True 
       ExtractNumber = ExtractNumber & ref 
      Case Else 
       If foundnumber = True Then Exit For 
     End Select 
    Next 

End Function 
5

沒有什麼不對您如何試圖完成這個任務,但我不能幫助自己從提示的正則表達式:-)

這個例子將剝去位於A1的字符串中的所有非數字字符並將結果呈現在消息框中。所用的圖案[^0-9]

Sub StripDigits() 
    Dim strPattern As String: strPattern = "[^0-9]" 
    Dim strReplace As String: strReplace = vbnullstring 
    Dim regEx As New RegExp 
    Dim strInput As String 
    Dim Myrange As Range 

    Set Myrange = ActiveSheet.Range("A1") 

    If strPattern <> "" Then 
     strInput = Myrange.Value 
     strReplace = "" 

     With regEx 
      .Global = True 
      .MultiLine = True 
      .IgnoreCase = False 
      .Pattern = strPattern 
     End With 

     If regEx.test(strInput) Then 
      MsgBox (regEx.Replace(strInput, strReplace)) 
     Else 
      MsgBox ("Not matched") 
     End If 
    End If 
End Sub 

請確保您添加的引用爲「Microsoft VBScript的正則表達式5.5」

有關如何在Excel中使用正則表達式,包括通過範圍check out this post循環的示例的詳細信息。

結果:

enter image description here

+0

不錯,我在考慮使用正則表達式,但不要足夠了解它寫什麼。好想法! – BruceWayne

+0

好方法。使用'vbnullstring'比''''更高效一點'' – brettdj

相關問題