2012-07-05 32 views
0

我試圖創建一個函數,該函數可以通過字符串給出數字的部分值。我試過的各種版本的工作效果都不盡如人意,我在http://www.utteraccess.com/forum/Find-number-string-Ins-t1746052.html上找到了一個代碼片段。VBA函數在特定情況下添加尾隨零

,我試圖從樣子拉值的字符串:
A11, A21A23, A25, A23A21, etc.
有幾個專門的情況下字符串是:
A23 D0, A23 D1, A23A21 D0, etc.

出於某種原因,在包括了d的情況下, ,代碼將爲D後的任意數量加上一個零。所以A23 D0返回:23,因爲它應該A23 D1,但是,返回230A23 D3返回23000,依此類推。

我對VBA相當陌生,我無法弄清楚會導致字母D添加尾隨零的位置,其他字母代替D的位置不會有相同的效果。

的VBA腳本如下:

Public Function GetNumFromStringFloating(strText As String, Optional intPos As Integer = 1) As String 
'? GetNumFromStringFloating("12*TLG AUTVTG18871890AAUG") = 12 
'? GetNumFromStringFloating("12*TLG AUTVTG18871890AAUG",3) = 12 
'? GetNumFromStringFloating("12*TLG AUTVTG18871890AAUG",14) = 18871890 
'? GetNumFromStringFloating("12*TLG AUTVTG18871890AAUG",-1) = 18871890 (Reverse Search) 
Dim X As Integer 
If intPos > 0 Then 
    For X = intPos To Len(strText) 
     If IsNumeric(Mid(strText, X, 1)) Then 
      GetNumFromStringFloating = val(Mid(strText, X) & "") 
      Exit For 
     End If 
    Next X 
Else 
    For X = Len(strText) To Abs(intPos) Step -1 
     If IsNumeric(Mid(strText, X, 1)) Then 
      GetNumFromStringFloating = val(Mid(strText, X) & "") 
     Else 
      If GetNumFromStringFloating <> "" Then Exit For 
     End If 
    Next X 
End If 
End Function 
+1

什麼是你的業務規則是什麼呢?什麼是輸入和什麼是你想要的輸出? – NoChance 2012-07-05 23:37:38

+0

Val存在一定的誤解(http://office.microsoft.com/en-us/access-help/val-function-HA001228931.aspx) – Fionnuala 2012-07-05 23:41:14

回答

1

像這樣的東西可能適合:

Function getnum(sText) 
''A11, A21A23, A25, A23A21 
Dim sNum As String 

''Skip the first letter 
For i = 2 To Len(sText) 
    If IsNumeric(Mid(sText, i, 1)) Then 
     sNum = sNum & Mid(sText, i, 1) 
    Else 
     Exit For 
    End If 
Next 

getnum = sNum 
End Function