aurelius89
Board Regular
- Joined
- Mar 15, 2017
- Messages
- 69
I have found a function that extracts the numbers from a cell:
I have tested this in my sheet by using =ExtractNumber(A1) and it works fine. If HBGR2342 was in cell A1 it would return 2342 as expected.
I now need to incorporate this in VBA to perform the number extraction on a range. I have put together the below but it doesn't work.
How can I make this function perform on a range of cells?
Code:
Function ExtractNumber(rCell As Range, _
Optional Take_decimal As Boolean, Optional Take_negative As Boolean) As Double
Dim iCount As Integer, i As Integer, iLoop As Integer
Dim sText As String, strNeg As String, strDec As String
Dim lNum As String
Dim vVal, vVal2
''''''''''''''''''''''''''''''''''''''''''
'Extracts a number from a cell containing text and numbers.
''''''''''''''''''''''''''''''''''''''''''
sText = rCell
If Take_decimal = True And Take_negative = True Then
strNeg = "-" 'Negative Sign MUST be before 1st number.
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
ExtractNumber = CDbl(lNum)
End Function
I have tested this in my sheet by using =ExtractNumber(A1) and it works fine. If HBGR2342 was in cell A1 it would return 2342 as expected.
I now need to incorporate this in VBA to perform the number extraction on a range. I have put together the below but it doesn't work.
Code:
Sub TakeNumbers()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("RefindData")
Dim c As Range
For Each c In ws.Range("G2:G2500").Cells
Call ExtractNumber(c)
Next c
End Sub
How can I make this function perform on a range of cells?