Share via

Create a Macros Function

Anonymous
2025-04-17T13:48:00+00:00

Hello everyone, I would like help with a VBA macro. This macro only extracts numbers, but I can't update it so that the extraction form includes a special character "-" or "/" as shown in the example below.

"00000-000"

“0000/000"

“000/00”

“000-00”

When used, it automatically excludes the "-" or "/"

Can anyone help me?

Function GetNumber(CellRef As String)

Dim StringLength As Integer

StringLength = Len(CellRef)

For i = 1 To StringLength

If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1)

Next i

GetNumber = Result

End Function

Microsoft 365 and Office | Excel | For education | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

3 answers

Sort by: Most helpful
  1. Andreas Killer 144.1K Reputation points Volunteer Moderator
    2025-04-17T15:35:56+00:00

    Here is the fastest function I've ever seen for this task.

    Andreas.

    Function JustNumbers(ByVal What As String) As String
      'Return only numbers from What (by Rick Rothstein)
      Dim i As Long, j As Long, Digit As String
      For i = 1 To Len(What)
        Digit = Mid$(What, i, 1)
        If Digit Like "#" Then
          j = j + 1
          Mid$(What, j, 1) = Digit
        End If
      Next
      JustNumbers = Left$(What, j)
    End Function
    

    Was this answer helpful?

    0 comments No comments
  2. Anonymous
    2025-04-17T14:17:27+00:00

    Thank you very much!

    Was this answer helpful?

    0 comments No comments
  3. HansV 462.6K Reputation points
    2025-04-17T14:04:45+00:00

    If you want to include "-" and "/" in the result:

    Function GetNumber(CellRef As String)
        Dim StringLength As Integer
        Dim i As Long
        Dim c As String
        Dim Result As String
        StringLength = Len(CellRef)
        For i = 1 To StringLength
            c = Mid(CellRef, i, 1)
            If IsNumeric(c) Or c = "-" Or c = "/" Then
                Result = Result & c
            End If
        Next i
        GetNumber = Result
    End Function
    

    Was this answer helpful?

    0 comments No comments