2012-12-13 73 views
0

我在excel中的字符串可以是任何像213221-sddc或232323/scdscsd或数字和字符之间的任何分隔符......我怎样才能从这个文本中提取数字?如何从字母数字文本中提取数字?

+0

,因为我的手比较痒我写了一个代码参照我从评论中提到的功能。所以没有交叉发布。但要让您了解如何读取Excel单元格范围以处理文本然后输出。希望让你去;) – bonCodigo

+1

当你可以使用正则表达式时,不需要太多的代码 – InContext

+1

如果你的数字总是在字符串的前面,那么正则表达式是矫枉过正的。 – brettdj

回答

2

这仅仅是一个开始,你可以从一系列阅读你的所有字母数字文字(根据图像),然后使用ABOVE MENTIONED FUNCTION From Dave and Richie

Option Explicit 

Sub TestRange() 
Dim numberArray As Variant 
Dim i As Integer 
Dim strTemp As String 

    numberArray = Application.Transpose(Sheets(1).Range("B4:B11")) 

    For i = LBound(numberArray) To UBound(numberArray) 
     strTemp = numberArray(i) 
     numberArray(i) = ExtractNumber(strTemp) '-- **You use above mentioned function** 
    Next i 

'Output the processed array into the Sheet. 
Sheets(1).Range("C4").Resize(UBound(numberArray), _ 
LBound(numberArray)) = Application.Transpose(numberArray) 

End Sub 

输出:

enter image description here

5

使用正则表达式。我已经将strNoAlpha作为Double加入,但如果需要,这也可以是一个字符串。

Dim str As String, strNoAlpha As Double 

str = "213221-sddc" 
With CreateObject("vbscript.regexp") 
    .Pattern = "[^\d]+" 
    .Global = True 
    strNoAlpha = Trim(.Replace(str, vbNullString)) 
End With 

或者作为UDF:

Function removeAlpha(rng As Range) As Double 

    If (rng.Count <> 1) Then 
     removeAlpha = "Only select one cell" 
     Exit Function 
    End If 

    Dim str As String 

    str = rng.Value2 

    With CreateObject("vbscript.regexp") 
     .Pattern = "[^\d]+" 
     .Global = True 
     removeAlpha = Trim(.Replace(str, vbNullString)) 
    End With 

End Function 
+1

+ 1用于RegEx。你可能也想使用'Trim(strNoAlpha)'去除空格? –

+0

空格被\ d删除,只返回数字,但通常是一种很好的技术。 – InContext

+0

'strNoAlpha = .Replace(str,vbNullString)'不会删除空格...试试这个'Debug.Print Len(Trim(strNoAlpha))'和'Debug.Print Len(strNoAlpha)'第一个会给你6,第二个会给你8 ... –