Extract number from string in VBA

后端 未结 4 1472
攒了一身酷
攒了一身酷 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:16

    This will extract the first number in a string:

    Public Function GetNumber(s As String) As Long
        Dim b As Boolean, i As Long, t As String
        b = False
        t = ""
        For i = 1 To Len(s)
            If IsNumeric(Mid(s, i, 1)) Then
                b = True
                t = t & Mid(s, i, 1)
            Else
                If b Then
                    GetNumber = CLng(t)
                    Exit Function
                End If
            End If
        Next i
    End Function
    

    enter image description here

    0 讨论(0)
  • 2020-12-21 10:17

    Have you considered using the "Split" function in VBA? If it is always pipe delimited, you could try:

    Public Function extractQLlMax(cellRow, cellColumn) As String
        Dim X as Variant
        qlm = Cells(cellRow, cellColumn).Value
        extractQLlMax = qlm
    
        If extractQLinfoBool = "Yes" And Not InStr(1, qlm, "IN") = 0 Then
            If InStr(1, qlm, "QUANTITY SUPPLY") > 0 Then
            x = Split(qlm,"|")
            extractQLlMax = X(ubound(x))
        ElseIf extractQLinfoBool = "Yes" And Not InStr(1, qlm, "FILL") = 0 Then
            perIndex = InStr(1, qlm, "PER")
            extractQLlMax = Mid(qlm, 1, perIndex - 2)
        End If
    End Function
    
    0 讨论(0)
  • 2020-12-21 10:17

    You might pass an optional parameter in to distinguish which number you want to pull.

    Public Function days_supply(blurb As String, Optional i As Long = 1)
        Dim sTMP As String
        sTMP = Trim(Split(blurb, "|")(1))
    
        If i = 1 Then
            days_supply = CLng(Trim(Left(Replace(sTMP, " ", Space(99)), 99)))
        Else
            sTMP = Trim(Mid(sTMP, InStr(1, LCase(sTMP), " in ", vbTextCompare) + 4, 9))
            days_supply = CLng(Trim(Left(Replace(sTMP, " ", Space(99)), 99)))
        End If
    End Function
    

        VBA text parsing Split

    The formula in B1 is,

    =days_supply(A1)
    

    The formula in C1 is,

    =days_supply(A1,2)
    
    0 讨论(0)
  • 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)
    0 讨论(0)
提交回复
热议问题