Extract maximum number from a string

前端 未结 4 854
灰色年华
灰色年华 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:08

    Here is some VBA (not vbscript) that you can adapt to you needs:

    Public Function MyCode(ByVal txt As String) As String
        Dim maxi As Double, db As Double
        maxi = -9999
        arr = Split(Replace(txt, "=", ","), ",")
        For Each a In arr
            If IsNumeric(a) Then
                db = CDbl(a)
                If db > maxi Then maxi = db
            End If
        Next a
        MyCode = CStr(maxi)
    End Function
    

    NOTE:

    This gives a String and not a Number.

    EDIT#1:

    In Excel-VBA, the code must be placed in a standard module.

    User Defined Functions (UDFs) are very easy to install and use:

    1. ALT-F11 brings up the VBE window
    2. ALT-I ALT-M opens a fresh module
    3. paste the stuff in and close the VBE window

    If you save the workbook, the UDF will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

    To remove the UDF:

    1. bring up the VBE window as above
    2. clear the code out
    3. close the VBE window

    To use the UDF from Excel:

    =MyCode(A1)
    

    To learn more about macros in general, see:

    http://www.mvps.org/dmcritchie/excel/getstarted.htm

    and

    http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

    and for specifics on UDFs, see:

    http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx

    Macros must be enabled for this to work!

提交回复
热议问题