从字符串中获取适当的最大数字

时间:2019-01-15 17:08:01

标签: excel vba

我的字符串是su=45, nita = 30.8, raj = 60, gita = 40.8。这涉及到SO问题Extract maximum number from a string 我正在使用maxNums函数,结果为40.8,而我希望是60。代码行中的修改将为我提供所需的结果。下面的代码复制以避免交叉引用。如果此字符串包含所有数字用小数点表示,则可以得到正确的结果,但是从外部来源考虑的数据可以是整数。

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

3 个答案:

答案 0 :(得分:2)

您的代码存在一两个问题。第一个是正则表达式不查找十进制数字。如果您将其更改为

.Pattern = "\d+\.?(\d?)+"

它将更好地工作。简而言之:
\ d + =至少一位数字
。? =可选点
(\ d?)+ =可选数字

这不是防水的表达,但至少在一定程度上有效。

第二个问题是十进制符号不同的潜在问题,在这种情况下,您需要进行一些搜索和替换,然后再处理。

答案 1 :(得分:0)

如果它总是 x = number ,我认为遍历每个定界值会更简单,然后读取=作为值:

Function MaxValue(data As String)
    Dim i As Long, value As Double
    Dim tokens() As String: tokens = Split(data, ",")

    For i = 0 To UBound(tokens)
        '// get the value after = as a double
        value = CDbl(Trim$(Mid$(tokens(i), InStr(tokens(i), "=") + 1)))
        If (value > MaxValue) Then MaxValue = value
    Next
End Function

答案 2 :(得分:0)

没有Regex

Public Function maxNums(str As String) As Double
    Dim i As Long, L As Long, s As String, wf As WorksheetFunction, brr()
    Set wf = Application.WorksheetFunction
    L = Len(str)

    For i = 1 To L
        s = Mid(str, i, 1)
        If s Like "[0-9]" Or s = "." Then
        Else
            Mid(str, i, 1) = " "
        End If
    Next i

    str = wf.Trim(str)
    arr = Split(str, " ")

    ReDim brr(LBound(arr) To UBound(arr))

    For i = LBound(arr) To UBound(arr)
        brr(i) = CDbl(arr(i))
    Next i

    maxNums = wf.Max(brr)
End Function

enter image description here