excel中的字符串可以是213221-sddc或232323 / scdscsd之类的字符串,也可以是数字和字符之间的任何分隔符...我如何只提取此文本中的数字?
答案 0 :(得分:6)
使用正则表达式。我已将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 :(得分: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
输出:
答案 2 :(得分:0)
测试:
Public Sub AlphaNumericTest()
Dim AlphaNumericStr As String
AlphaNumericStr = "A100"
Dim SeqStartNum As Double, SeqStartAlpha As String
SeqStartNum = NumericBreakdown(AlphaNumericStr)
SeqStartAlpha = AlphaBreakdown(AlphaNumericStr)
Debug.Print "Seq Alpha = " & SeqStartAlpha
Debug.Print "Seq Num = " & SeqStartNum
End Sub
Alpha部分的功能
Public Function AlphaBreakdown(str As String) As String
With CreateObject("vbscript.regexp")
.Pattern = "[^\D]+"
.Global = True
AlphaBreakdown = Trim(.Replace(str, vbNullString))
Debug.Print "Alpha = " & AlphaBreakdown
End With
End Function
数字部分功能:
Public Function NumericBreakdown(str As String) As Double
With CreateObject("vbscript.regexp")
.Pattern = "[^\d]+"
.Global = True
NumericBreakdown = Trim(.Replace(str, vbNullString))
Debug.Print "Numeric = " & NumericBreakdown
End With
End Function