Extract number from string in VBA

后端 未结 4 1501
攒了一身酷
攒了一身酷 2020-12-21 09:51

I have cells in vba that contain strings like this:

QUANTITY SUPPLY <= DAYS SUPPLY|30 IN 23 DAYS

I send these strings through two functions that just pick

4条回答
  •  情歌与酒
    2020-12-21 10:21

    This is by far the shortest (5 lines) function to extract the numbers!

    Function GetNumbers(str As String, Occur As Long) As Long
    Dim regex As Object: Set regex = CreateObject("vbscript.RegExp")
    regex.Pattern = "(\d+)"
    Regex.Global = True
    Set matches = regex.Execute(str)
    GetNumbers = matches(Occur)
    End Function
    

    Parameters:

    1. Str is the string to extract numbers from
    2. Occur is the occurrence of that number (it's 0-based so the first number will have the occurence of 0 not 1 and so on)

提交回复
热议问题