标签:VBA,自定义函数
下面是一个自定义函数,可以从文本中提取数字。这个函数来源于forum.ozgrid.com,辑录于此,供参考。
代码:
Function ExtractNumber(rCell As Range, _
Optional Take_decimal As Boolean, _
Optional Take_negative As Boolean) As Double
Dim iCount As Integer
Dim i As Integer
Dim iLoop As Integer
Dim sText As String
Dim strNeg As String
Dim strDec As String
Dim lNum As String
Dim vVal, vVal2
Dim c As Range
For Each c In rCell
sText = c
If Take_decimal = True And Take_negative = True Then
strNeg = "-" '负号必须在第一个数字之前.
strDec = "."
ElseIf Take_decimal = True And Take_negative = False Then
strNeg = vbNullString
strDec = "."
ElseIf Take_decimal = False And Take_negative = True Then
strNeg = "-"
strDec = vbNullString
End If
iLoop = Len(sText)
For iCount = iLoop To 1 Step -1
vVal = Mid(sText, iCount, 1)
If IsNumeric(vVal) Or vVal = strNeg Or vVal = strDec Then
i = i + 1
lNum = Mid(sText, iCount, 1) & lNum
If IsNumeric(lNum) Then
If CDbl(lNum) < 0 Then Exit For
Else
lNum = Replace(lNum, Left(lNum, 1), "", , 1)
End If
End If
If i = 1 And lNum <> vbNullString Then lNum = CDbl(Mid(lNum, 1, 1))
Next iCount
If Not IsNumeric(lNum) Then lNum = 0
ExtractNumber = ExtractNumber + CDbl(lNum)
lNum = ""
Next
End Function
其中,参数rCell代表要包含数字内容的单元格;参数Take_decimal代表是否提取水小数值,布尔型,可选;参数Take_negative代码是否提取负值,布尔型,可选。
下图1为应用示例。
图1
欢迎在下面留言,完善本文内容,让更多的人学到更完美的知识。