Advertisement
Guest User

Untitled

a guest
May 26th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. Sub extractNumbersFromCells()
  2. '
  3. '
  4. ' Extract numbers from cells in selected range
  5. '
  6. Dim rng As Range
  7. Dim Last As Long
  8. Last = ActiveSheet.UsedRange.Rows.Count
  9.  
  10. For Each rng In Selection
  11. If rng.Row > Last Then Exit For
  12. If rng.Value <> "" And Not rng.Value Like "q*" Then 'note use of wildcard here
  13. rng.Value = ExtractNumber(rng, False, False) 'function has a lot more capabilities than what I'm using it for here
  14. End If
  15.  
  16. Next rng
  17.  
  18. End Sub
  19. '______________________________________________________________________________________________________
  20. Function ExtractNumber(rCell As Range, Optional Take_decimal As Boolean, Optional Take_negative As Boolean) As Double
  21.  
  22.  
  23.  
  24. Dim iCount As Integer, i As Integer, iLoop As Integer
  25.  
  26. Dim sText As String, strNeg As String, strDec As String
  27.  
  28. Dim lNum As String
  29.  
  30. Dim vVal, vVal2
  31.  
  32.  
  33.  
  34. ''''''''''''''''''''''''''''''''''''''''''
  35.  
  36. 'Written by OzGrid Business Applications
  37.  
  38. 'www.ozgrid.com
  39.  
  40. 'Extracts a number from a cell containing text and numbers.
  41.  
  42. ''''''''''''''''''''''''''''''''''''''''''
  43.  
  44. sText = rCell
  45.  
  46. If Take_decimal = True And Take_negative = True Then
  47.  
  48. strNeg = "-" 'Negative Sign MUST be before 1st number.
  49.  
  50. strDec = "."
  51.  
  52. ElseIf Take_decimal = True And Take_negative = False Then
  53.  
  54. strNeg = vbNullString
  55.  
  56. strDec = "."
  57.  
  58. ElseIf Take_decimal = False And Take_negative = True Then
  59.  
  60. strNeg = "-"
  61.  
  62. strDec = vbNullString
  63.  
  64. End If
  65.  
  66. iLoop = Len(sText)
  67.  
  68.  
  69.  
  70. For iCount = iLoop To 1 Step -1
  71.  
  72. vVal = Mid(sText, iCount, 1)
  73.  
  74.  
  75.  
  76.  
  77.  
  78. If IsNumeric(vVal) Or vVal = strNeg Or vVal = strDec Then
  79.  
  80. i = i + 1
  81.  
  82. lNum = Mid(sText, iCount, 1) & lNum
  83.  
  84. If IsNumeric(lNum) Then
  85.  
  86. If CDbl(lNum) < 0 Then Exit For
  87.  
  88. Else
  89.  
  90. lNum = Replace(lNum, Left(lNum, 1), "", , 1)
  91.  
  92. End If
  93. End If
  94.  
  95.  
  96. If i = 1 And lNum <> vbNullString Then lNum = CDbl(Mid(lNum, 1, 1))
  97.  
  98. Next iCount
  99.  
  100. ExtractNumber = CDbl(lNum)
  101.  
  102. End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement