我在 excel 中的字符串可以是 213221-sddc 或 232323/scdscsd 或数字和字符之间的任何分隔符......我怎样才能从这个文本中只提取数字?
问问题
2194 次
3 回答
7
使用正则表达式。我已将 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
于 2012-12-13T14:05:36.077 回答
2
这只是一个开始,您可以从一个范围(根据图像)读取所有字母数字文本,然后使用Dave 和 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
输出:
于 2012-12-13T12:56:46.103 回答
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
于 2020-12-17T19:50:39.060 回答