Extract maximum number from a string

前端 未结 4 855
灰色年华
灰色年华 2021-01-24 15:57

I am trying to extract all numbers from a string with a function in Excel. In the second time, I would like to extract the maximum value contains in the string.

4条回答
  •  旧巷少年郎
    2021-01-24 16:10

    Collect all of the mixed numbers as doubles in an array and return the maximum value.

    Option Explicit
    Option Base 0    '<~~this is the default but I've included it because it has to be 0
    
    Function maxNums(str As String)
        Dim n As Long, nums() As Variant
        Static rgx As Object, cmat As Object
    
        'with rgx as static, it only has to be created once; beneficial when filling a long column with this UDF
        If rgx Is Nothing Then
            Set rgx = CreateObject("VBScript.RegExp")
        End If
        maxNums = vbNullString
    
        With rgx
            .Global = True
            .MultiLine = False
            .Pattern = "\d*\.\d*"
            If .Test(str) Then
                Set cmat = .Execute(str)
                'resize the nums array to accept the matches
                ReDim nums(cmat.Count - 1)
                'populate the nums array with the matches
                For n = LBound(nums) To UBound(nums)
                    nums(n) = CDbl(cmat.Item(n))
                Next n
                'test array
                'Debug.Print Join(nums, ", ")
                'return the maximum value found
                maxNums = Application.Max(nums)
            End If
        End With
    End Function
    

提交回复
热议问题