文本排序中的最小/最大值

4
在SQL Server中,MIN和MAX可以处理不可转换为数字的文本,并返回按文本排序顺序最低或最高的文本项,或者按照SQL Server术语所称的"排序顺序"。但是在Excel中是否有这样的功能而无需自定义函数进行排序呢?
例如,对于MIN("bb","aa","cc"),返回"aa";对于MAX("bb","cc","aa"),返回"cc"。
Excel的MIN/MAX忽略文本,虽然MINA/MAXA可用于文本,但它们在无法解析为数字的文本上会出错。LARGE/SMALL也不行。
顺便说一下,一个同事问我如何在透视表中完成此操作。我认为除了使用自定义函数外,没有其他方法。请您自行判断。
2个回答

5
这个数组公式看起来很有前途。由于它是一个数组,需要使用ctrl-shift-enter进行输入。
最大值:
=INDEX(A2:A6,MATCH(0,COUNTIF(A2:A6,">"&A2:A6), 0))

最小值:

=INDEX(A2:A6,MATCH(0,COUNTIF(A2:A6,"<"&A2:A6), 0))

将三个范围更改为您想要的内容。

最大值和最小值版本相同,除了 ><


我已编辑答案(等待批准),将match()的第三个参数从默认值(=1)更改为0。默认值要求第二个参数的范围按升序排序。虽然我没有测试过,但由于答案没有说明需要这样做,我认为不需要,因此第三个参数应该是零。如果我错了,请纠正我。(Match()文档:https://support.office.com/en-us/article/match-function-e8dffd45-c762-47d6-bf89-533f4a37673a) - NewSites

3

我认为你是正确的,使用自定义函数是最好的选择。需要注意的是,通常的比较运算符与你所描述的类似。

Public Function MinStr(ByVal strVal As Range) As String
    Dim i As Integer
    Dim cell As Range
    MinStr = ""

    'Check to make sure the range is not empty
    if strVal.Rows.Count > 0 then
        'Initialize MinStr to a known value
        MinStr = strVal.cells(1,1).Value

        'Iterate through the entire range
        For Each cell in strVal.Cells
            if(MinStr > cell.Value) then
                MinStr = cell.Value
            end if
        Next cell
    end if
End Function

Public Function MaxStr(ByVal strVal As Range) As String
    Dim i As Integer
    Dim cell As Range
    MaxStr = ""

    'Check to make sure the range is not empty
    if strVal.Rows.Count > 0 then
        'Initialize MaxStr to a known value
        MaxStr = strVal.cells(1,1).Value

        'Iterate through the entire range
        For Each cell in strVal.Cells
            if(MaxStr < cell.Value) then
                MaxStr = cell.Value
            end if
        Next cell
    end if
End Function

当我尝试使用“input”作为变量名称时,它不喜欢它,否则很好,如果可以进行编辑,则+1。 - Tom Sharpe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接